import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { View, Text } from 'react-native';
const PostsList = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.defaults.headers.common['Authorization'] = 'mykey';
axios.get('http://myurl')
.then(res => {
setPosts(res.data);
})
.catch(error => console.error(error));
}, []);
return (
<View>
{posts.map(post => (
<Text key={post.id}>{post.title.rendered}</Text>
))}
</View>
);
};
export default PostsList;
I'm asking help because I have a problem with React Native and the WordPress REST API. I am trying to access it with Axios but it returns the following error: ERROR [AxiosError: Network Error]
I am using Expo and testing it on my own Android device (not an emulator). It should be noted that my WordPress is hosted locally and I have tried specifying my IP, but to no avail. Does anyone can help me please ?
Thank you.
I tried to put my own ip and to disable my firewall
Related
I'm a beginner in NextJs and I'm having trouble fetching an image already stored in firebase storage to my website.
I've tried several solutions and none of them are working.
At this moment the console returns me this error:
"Image is missing required "src" property".
I didn't find much concrete information about this on google. I'm sure it will be useful for a lot of people.
I hope someone can help me, I've been stuck here for over 24 hours..
Here is my code:
import { useState, useEffect } from "react";
import { firebaseConfig } from "#/firebase/firebase";
import { initializeApp } from "#/firebase/firebase";
import { getStorage, ref, getDownloadURL } from "firebase/storage"
import styles from "../../styles/collections.module.css"
initializeApp(firebaseConfig);
export default function Test() {
const [url, setUrl] = useState();
useEffect(() => {
const func = async () => {
const storage = getStorage();
const reference = ref(storage, 'collections/amsterdam/bedroom/image10.avif');
await getDownloadURL(reference).then((x) => {
setUrl(x);
})
}
func();
}, []);
return (
<div className={styles.test}>
<div className={styles.test_container}>
<h1>Fetching image from firebase to NextJs project.</h1>
<Image
source={{ uri:url }}
width={500}
height={500}
alt=""
/>
</div>
</div>
)
}````
As the error states, you need to define the "src" property
<Image
src={url}
width={500}
height={500}
alt=""
/>
In Nextjs 13 - experimental app directory, if I wanted to use useState on the root layout/page I must add ‘use client’ to the code, which effectively prevents all nested components from being server components.. how can I work around this so that I can use useState and still have server components. Thanks to any responders.
I don't know if this answers to your question (it's better to add some example code to help users understand your problem)
If you create a Server Component, and in that component you add your Client Component, it works fine. For example
ClientComponent.tsx
"use client";
import {useState} from 'react';
export default function ClientComponent() {
const [count, setCount] = useState(0);
return (
<>
<h1>Client Component</h1>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
)
}
ServerComponent.tsx
async function getData(){
const res = await fetch('http://localhost:3000/api/hello');
return await res.json();
}
export default async function ServerComponent() {
const data = await getData()
return (
<>
<h1>Server Component</h1>
<p>{data.name}</p>
</>
)
}
Api hello.ts
export default async function handler(req, res) {
res.status(200).json({ name: 'John Doe' })
}
Your page
import ClientComponent from "./ClientComponent";
import ServerComponent from "./ServerComponent";
export default function Page() {
return(<>
<ClientComponent/>
<ServerComponent/>
</>
)
}
In this example ServerComponent is rendered on the server, but ClientComponent on the client so it maintain interactivity
Hope this will help
I keep getting the following error and my app crashes when I try to use the method createUserWithEmailAndPassword or signInWithPhoneNumber from RNFirebase on my react native app. This is currently happening only on the android version of my app.
I did all that was mentioned in the documentation, including enabling Android Device Verification API on my Google Cloud Platform while I was trying to have the signInWithPhoneNumber method work.
I kept on getting the above-mentioned error on Android 7.0 on a Samsung S6 and Huawei Nova 2i.
Below is the code I used:
import { View, Text } from 'react-native'
import React, { useState } from 'react'
import styles from './styles'
import { Button, TextInput } from 'react-native-paper'
import auth from '#react-native-firebase/auth';
function LoginScreen() {
const [emailID, setEmailID] = useState("");
const [password, setPassword] = useState("");
const [confirm, setConfirm] = useState(null);
const [code, setCode] = useState('');
async function loginWithEmail (email, password) {
await auth()
.createUserWithEmailAndPassword('jane.doe#example.com', 'SuperSecretPassword!')
.then(() => {
console.log('User account created & signed in!');
})
.catch(error => {
if (error.code === 'auth/email-already-in-use') {
console.log('That email address is already in use!');
}
if (error.code === 'auth/invalid-email') {
console.log('That email address is invalid!');
}
console.error(error);
});
}
return (
<View style={styles.container}>
<View style={styles.textInputContainer}>
<TextInput mode="outlined"
label='Enter your email'
keyboardType="email-address"
value={emailID}
onChangeText={(e) => setEmailID(e)} />
<TextInput mode="outlined"
label='Enter your password'
secureTextEntry
value={password}
onChangeText={(e) => setPassword(e)} />
</View>
<View style={styles.buttonContainers}>
<Button mode="contained" style={styles.signUpButton} disabled={emailID.length > 5 && password.length > 6 ? false : true} onPress={() => loginWithEmail(emailID, password)}>Login</Button>
</View>
</View>
)
}
export default LoginScreen
Any help in pointing out where I went wrong would be of great help. Thank you
i'm trying to send notification with firebase. i wanna get devices token (senderID) but when i run my code the app shut down immediately
please look at my code and tell me where is my mistake
import React,{useEffect} from 'react'
import { View, Text } from 'react-native'
import messaging from '#react-native-firebase/messaging'
const checkToken = async () => {
try {
const fcmToken = await messaging().getToken();
if (fcmToken) {
console.log(fcmToken);
}
} catch (error) {
console.error(error);
}
};
const App = () => {
useEffect(() => {
checkToken()
}, [])
return (
<View>
<Text>sadasdasfdasdafsfdasfdasdafsdf</Text>
</View>
)
}
export default App
I am new using native react, I am developing a project that consists in showing the data of an Api in my project. I have seen tutorials and most, if not all, use the same Api:
But what I want is to be able to show the data of a local API that connects to a local BD as well, which is why I developed a Web API with ASP.Net, I was guided by this
Create a DB in SQL Server (which is the DB that I want to use for this project) and generate the API; the API works correctly, tested with POSTMAN.
Now the problem is that I want to use it in my project, and following the tutorial that is on the official page of React Native in the section does not work for me.
This is my code:
import React from 'react';
import { FlatList, ActivityIndicator, Text, View } from 'react-native';
export default class FetchExample extends React.Component {
constructor(props){
super(props);
this.state ={ isLoading: true}
}
componentDidMount(){
return fetch('http://192.168.2.19:53943/api/users')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.users,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render(){
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return(
<View style={{flex: 1, paddingTop:20}}>
<FlatList
data={this.state.dataSource}
renderItem={({item}) => <Text>{item.Name}, {item.Email}</Text>}
keyExtractor={({id}, index) => id}
/>
</View>
);
}
}
The error message that I get when I execute my project is THIS
JSON Parse Error: Unrecognized Token
What could I be doing wrong? I suspect that it may be the URL that happened to the FETCH, since it eliminates all of the render () and only leaves a showing a message and the same error keeps coming up. Thank you
hi you shuld add this code in Global.asax Application_Start() :
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
and add this code in WebApiConigg :
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
rest visual stdio and run again project WebApi address
stop react-native emulator => cntrl+ c react-native-run-android