-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
– Rafael Tavares