How to Set State of Response from Axios in React

How to set state of response from axios in react

You have a syntax error here. You should try this instead

var self = this;
axios.get('/url')
.then(function (response) {
console.log(response);
self.setState({events: response.data})
})
.catch(function (error) {
console.log(error);
});
//the rest of the code
var a = 'i might be executed before the server responds'

There are a few things to note here:

  • axios.get is an asynchronous function which means that the rest of the code will be executed .And when the response of the server arrives, the function passed to then will be executed. The return value of axios.get('url') is called a promise object. You can read more about it here
  • this keyword has a different value depending of where it is called. this in this.setState should refer to the constructor object, and when you call this inside a function, it refers to the window object. That is why i assigned this to the variable self. You can read more about this here

Pro tip:

If you use ES6, you would want to use arrow functions (which don't have their own this) and use this.setState without assigning this to a variable. more about it here

    axios.get('/url')
.then((response) => {
console.log(response);
this.setState({events: response.data})
})
.catch((error)=>{
console.log(error);
});

Here is a complete example https://codesandbox.io/s/rm4pyq9m0o containing best practices commonly used to fetch data including error handling, try again and loading. This provides a better User experience. You are encouraged to modify the code and play around to get more insights about it.

ReactJS - setState Axios POST response

if you don't get this.setState is undefined error then it's a bit strange. Could you fix/copy the code below and verify if that helps:

import React, { Component } from 'react';
import axios from 'axios';
import Todos from "./Components/Todos"

class App extends Component {
constructor(props){
super(props); // pass props to "father" constructor
this.state = {
todos:[]
}
this.getTodos = this.getTodos.bind(this);
}

// AXIOS request
getTodos(){
var postData = {
"startDate": "startDate",
"endDate": "endDate",
"studentGroup": ["ID"]
};
let axiosConfig = {
headers: {
'Content-Type': 'application/json',
'Authorization': "Basic " + btoa("username" + ":" + "password")
}
};
axios.post('url', postData, axiosConfig)
.then((response) => {
if(response.data.reservations) {
this.setState({todos: response.data.reservations})
}
})
.catch((err) => {
console.log("Error: ", err);
})
}

componentDidMount(){
this.getTodos();
}

render() {
console.log(this.state.todos);
return (
<div className="App">
<Todos todos={this.state.todos}/>
</div>
);
}
}
export default App;

Now observe if console.log(this.state.todos); is called after the request is finished. If so, verify it's an empty array.

ReactJs - can't access setState inside axios call

When you call a function (non arrow function), this is always an implicit parameter.

Normal functions

By normal functions I mean functions that are not methods.

In strict mode value of this is always undefined.

And in non strict mode value of this is always the global object (window in browsers)

function foo() {
"use strict";
return this;
}

function bar() {
return this;
}

console.log(foo() === undefined); // true
console.log(bar() === window); // true

React can't set state after axios request

It takes time to set the state using hooks as it is asynchronous function. Try using this in your code

import Axios from 'axios'

function Menu() {
const[items,setItems]=useState([])

useEffect(async()=>{
await Axios.get('http://localhost:3001/read').then((response)=>{
console.log('DATA IS',response.data)
setItems(response.data)
console.log('items>>>>,',items)
})
},[])

useEffect(()=>{
console.log(items);
},[items]);

return (
//some JSX
)
}

Render axios response in Reactjs

Best practice to resolve promise outside the JSX. You can use bellow approach if you like.

const [items, setItems] = useState([]);

const fetch = () => {
axios
.get("http://localhost:5000/popular-products")
.then((response) => setItems(response.data));
};

// component did mount
useEffect(() => {
fetch();
}, []);

return (
<div className="App">
{items.length > 0 && items.map((item) => <p key={item.id}>{item.prod_name}</p>)}
</div>
);

In here I have used component did mount to fetch data when component mounted.

How to set state from an Axios get request without causing a re-render

  const [sentenceData, setSentenceData] = React.useState({})

React.useEffect(() => {
axios.get('http://localhost:3030/getrandomunusedsentence')
.then(() => {
setSentenceData(response.data[0])
})
}, [])

React setState if Axios.get response data is good

You can try this out. Just filter your movie data before setting the state.

axios.get(url)
.then(res => {
if (res.data) {
const movieData = res.data.results.filter(movie => movie.poster_path != null);
this.setState({movies: movieData}, () => {
console.log(this.state.movies);
});
}
}


Related Topics



Leave a reply



Submit