Issue
Here is the error! Displays on the server-side.
TypeError: Cannot read property ‘first_name’ of undefined
And the front-end component values are also not changed.
Here is the code
const [firstName,changeName] = useState("");
const [username,changeUsername] = useState("");
const user = useSelector(state => state.User);
const [id,changeId] = useState(user.id);
React.useEffect(()=>{
axios.get(url+id).then(function(response){
console.log("First Name");
console.log(id);
changeName(response.data[0].first_name);
});},[]);
There is no error with the get methods. I checked them before implementing this code. Can anyone help me to figure out this problem?
Solution
you missed adding the user state as a dependency to useEffect, your effect won’t get an updated value.
Try this:
const [firstName,changeName] = useState("");
const [username,changeUsername] = useState("");
const user = useSelector(state => state.User);
const [id,changeId] = useState(user.id);
React.useEffect(()=>{
axios.get(url+user.id).then(function(response){
console.log("First Name");
console.log(id);
changeName(response.data[0].first_name);
});},[user]);