Why React-Native doesn't show data fetched by Axios? - javascript

I've installed axios by this command:
npm i axios
I wrote the code below and everything I think is correct but React-Native doesn't show any data and throw any errors:
import React, {useState, useEffect} from 'react';
import axios from 'axios';
import {
View,
Text,
StyleSheet
} from 'react-native';
const App = () => {
const [data, setData] = useState([]);
useEffect(() => {
axios.get('http://localhost:8000/posts').then(res => {
setData(res.data);
});
}, []);
return (
<View style={styles.mainBody}>
{
data.map(item => (
<View>
<Text>{item.fields.title}</Text>
</View>
))
}
</View>
);
};
I've tested functional and class-based components for this.
I fetch data with Postman and works correctly.
I added .catch and it shows this: Error: Network Error
But it doesn't work on React-Native and because of no errors, I can't understand what's my problem. Any help will be appreciated.

It's because you're using localhost in your URL, with react-native we cant use localhost but instead, we use the IPv4 address of our computer. So click on your wifi icon then click on the properties then look for IPv4 address something like: 193.93.443
So if to say your IPv4 address is 193.93.443, the local URL will be like this: http://193.93.443:8000/posts

Related

calling a function only one time outside of useEffect react native

I have a function for setting up push notifications which needs to be called one time after the user logs in. This has to be outside of useEffect because the documentation says so.
I tried calling it in the component which comes after the user logs in, but the function is called 3 times after app is opened from killed state. Is there a way to limit this call to only one?
Here is the code so far:
const HomeScreen: FC<Props> = ({navigation}) => {
setupPushNotifications();
return (
<SafeAreaView style={homeStyles.wrapper}>
<Header navigation={navigation} />
<View style={homeStyles.container}>
...
...
One way to do it would have been to use constructor in react classes, but the whole application is written in ES6 and relies too much on hooks.
Is there any other way i can make this work?
You can call this in your main file index.js in root directory of your project
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
setupPushNotifications();
AppRegistry.registerComponent(appName, () => App);
But you said you want to call it only if user is logged in then in the same file where you placed setupPushNotifications just update the position of it and move it out side class block.
setupPushNotifications();
const HomeScreen: FC<Props> = ({navigation}) => {
...
}

React, getting Uncaught TypeError: Cannot read properties of undefined (reading 'map') on some refreshes

I have a simple server that listens on port 8000 and all it does is to return the name of the files inside a directory in this format:
{'Files': ['file1', 'file2', ...]}
I have a React app, that fetches the data using the useEffect hook and then places the response with the useState hook.
The problem is that, on the first try it works perfectly, and maybe on the second time as well, but when I refresh for the third time (or more) it just disappears! and I see an error message on the chrome devtools:
Uncaught TypeError: Cannot read properties of undefined (reading 'map')
The React code is:
import './App.css';
import {useEffect, useState} from "react";
function App() {
const [file, setFile] = useState();
useEffect(() => {
async function fetchData() {
const files = await fetch('http://localhost:8000/get_directory?dir=E:\\Learning\\LearningNetworking\\MD')
const file_json = await files.json()
setFile(file_json.File)
}
fetchData()
}, [])
return (
<div className="App">
<header className="App-header">
{file.map(file_name => <p>{file_name}<br/></p>)}
</header>
</div>
);
}
export default App;
I really don't know what's going on, maybe there's a race condition and the react app tries to render the list before fetching it? But doesn't the React useEffect hook knows when to fetch again and when not?
I tried using the nullish coalescing on this line:
const file_json = await files.json() ?? []
instead of:
const file_json = await files.json()
The server (if needed for debugging reasons) written in fastapi:
from pathlib import Path
from fastapi import FastAPI, Request
from starlette.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(CORSMiddleware,
allow_origins=['*'])
#app.get('/get_directory')
def directory_tree(request: Request):
path = request.query_params.get('dir', None)
return {'Files': [file.name for file in Path(path).iterdir()]}
I'm pretty sure I've got something wrong here in my understanding of React, I am a newbie so I would appreciate your help! Any searches online did not find exactly this problem (maybe it's because I couldn't phrase the problem very well... sorry if it has been asked before!).
The problem is coming from your client code. As you defined it, initially file is undefined. And since fetching data is asynchronous, sometimes the render happens before you get the data. One way to solve this issue is to initiate your state like this:
const [file, setFile] = useState([]);

Axios post requests are not working with events using ReactJS

Been quite stuck for the past week or so and cannot find any answers to my issue. Today I started doing some proper investigating. It looks like Axios is not working when firing events. This also does not work on my main PC either which makes me think it's actually a bug with Axios.
I have already tried:
Reinstalling Axios independently
Uninstalling all global dependencies I have
Creating a new React App
Checking the events are firing (which they are)
Checking my network tab (nothing shows up)
My post request is working fine when just calling it as a function:
import React from "react";
import axios from "axios";
import "./App.css";
function App() {
const makeRequest = () => {
axios.post("http://localhost:5000");
};
makeRequest();
return <div className="app"></div>;
}
export default App;
Backend output: There was a post request!
However, my code does not work when using events, this goes for onClick and onSubmit (that's what I have tested anyway):
import React from "react";
import axios from "axios";
import "./App.css";
function App() {
const makeRequest = () => {
axios.post("http://localhost:5000");
};
return (
<div className="app">
<button onClick={makeRequest}>Post Request</button>
</div>
);
}
export default App;
No backend output or frontend output. Help would be much appreciated!
Edit: Something I forgot to mention was that fetch works absolutely fine, but I'd really rather use Axios where possible.
Change your const to a function and call it with an object passthrough method.
import React from "react";
import axios from "axios";
import "./App.css";
function App() {
function makeRequest (){
axios.post("http://localhost:5000");
};
return (
<div className="app">
<button onClick={() => makeRequest()}>Post Request</button>
</div>
);
}
export default App;
Try to add more console.log calls to grab more debug data from frontend - it can help to solve the problem.
import React from "react";
import axios from "axios";
import "./styles.css";
export default function App() {
const makeRequest = () => {
const result = axios
.post("https://jsonplaceholder.typicode.com/users")
.then((result) => {
console.log("Result", result);
})
.catch((error) => console.error("Error", error))
.finally(() => console.log("Request has been made"));
console.log("Result should be a Promise object", result);
};
return (
<div className="app">
<button onClick={makeRequest}>Post Request</button>
</div>
);
}
The code snippet above works totally fine. Check the code snippet here, and try to run it on your environment. If the information in console logs will not appear or either didn't help – dig into your environment and tools which you use to transpile JSX code, build JS and add that information to the question. Probably the problem is hidden somewhere in there.
Kindly check if you have "proxy": "localhost:5000" in your react app package.json file, this will allow React to proxy API requests to the Node.js server built with Express.
5000 is the node server port.
The problem is that your're passing the funcion instead of calling it.
I would try using an arrow funcion in onClick likt this :
onclick={()=> makeRequest()}
I can see you are not invoking the function with (), it should be makeRequest()

Axios keeps making https calls when I use an http url?

I am having trouble using an API as it keeps making an https call and not an http call. The https call is behind a paywall and the free version of the api only supports http calls. I am using https://weatherstack.com/ API.
I am using react with the axios package to make my HTTP calls.
import React, { useState, useEffect } from 'react'
import axios from 'axios'
const Weather = (props) => {
const [response, setResponse] = useState([])
const hook = () => {
axios
.get(`http://api.weatherstack.com/current?access_key=${process.env.REACT_APP_API_KEY}&query=${props.country.capital}`)
.then(response => {
console.log('promise fulfilled')
setResponse(response.data)
})
}
useEffect(hook, [])
console.log(response)
return (
<div>Temperature: {} </div>)
}
export default Weather
The error message I receive from the API is this
info: "Access Restricted - Your current Subscription Plan does not support HTTPS Encryption."
​​
type: "https_access_restricted"
The strange thing is about 20% of the time the call works and I can get my data, but it doesn't work most of the time. TIA

Invariant Violation: Tried to get frame for out of range index NaN - React Native

When finishing the React Native application, I came across this error.
As I understand it is a problem with FlatList.
I started useState of incidents as an empty array.
Does anyone know how it could solve?
GitHub project - Be The Hero
Ivalid Violation error - React Native
GitHub Gist
I had the same issue, and Goskula Jayachandra's comment keyed me in and solved the problem.
The error is because your FlatList is rendering before the data arrives, because of it incidents initially will be a promise, that's the reason you are getting the above error.
How do I prevent FlastList from rendering before data?
Follow along in the code snippet below, I've added descriptive comments.
import React, { useEffect, useState } from 'react';
import { FlatList, ActivityIndicator } from 'react-native';
const Toolbox = () => {
// Define state for loading, defining default value of true
const [isLoading, setLoading] = useState(true);
useEffect(() => {
// Get your data to populate the FlatList, then set your loading state to false
setLoading(false);
}, []);
return (
// Basic ternary operator: if isLoading (true), then display ActivityIndicator, else display FlatList
{isLoading ? (
<ActivityIndicator /> // Don't forget to include ActivityIndicator
) : (
<FlatList
//...
/>
)
}
);
};
export default Toolbox;

Categories

Resources