The set function of the state of the React is not actually receiving and passing on the values

Asked

Viewed 380 times

-2

I don’t know pq, but when I try to make a request for my backend, the state of "posts" does not receive the value of Answer.data. That is, the two "console.log" have different values, while Response.data is correct the second returns an empty array. What can be?

const [posts, setPosts] = useState([]);

useEffect(() => {
    async function postLoader() {
        const response = await api.get('/posts');
        setPosts(response.data);
        console.log(response.data);
        console.log(posts);
    }

    postLoader();
}, []);

"devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-airbnb": "^18.1.0",
    "eslint-config-prettier": "^6.11.0",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-prettier": "^3.1.3",
    "eslint-plugin-react": "^7.19.0",
    "eslint-plugin-react-hooks": "^2.5.1",
    "prettier": "^2.0.5"
  }
"dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "axios": "^0.19.2",
    "bootstrap": "^4.5.0",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "3.4.1"
  },

import axios from 'axios';

const api = axios.create({
    baseURL: 'http://localhost:3333',
});

export default api;
  • What exactly is the problem? I imagine your problem is not in the code shown. The value of a state is only updated after re-rendering the component, it will not change inside the useEffect

2 answers

1

setPosts(response.data); is an asynchronous method, it means that the new state is not set instantly. When the method console.log(posts) is called, the value of its state has not yet been changed, giving the impression that the new value is not being set.

To print the new value, use the hook useEffect and passing its variable in the dependency array posts. This way, once the state is changed, it will have the new value imprinted:

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

0

1. Remove the function postLoader() from within the useEffect(()=>{},[]), for reasons of readability;

2. The setPosts method and anyone coming from useState(), does not update immediately, ie this makes even you do setPosts(response.data); and then the console.log(posts) the variable posts will not be updated yet, because it takes a little bit plus.

3. I recommend you do so:

const [posts, setPosts] = useState([]);
useEffect(()=>{
    console.log(posts)
},[posts]) //passar a variavel 'posts' aqui fará com que este useEffect execute somente quando 'posts'  trocar de valor, ou seja um 'console.log()' aqui sempre exibirá correto.

useEffect(() => {    
    await postLoader();
}, []);`

async function postLoader() {
    const response = await api.get('/posts');
    setPosts(response.data);
    console.log(response.data);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.