Home > Software design >  React API request is being made before props are sent
React API request is being made before props are sent

Time:08-07

In my React project I'm trying to fetch some data from a database when a Link is pressed. When I do this, I can see that my props are undefined which causes a blank React page to be rendered.

I verified that id was not undefined as a prop by logging it when the Link is pressed. However, when I log it in the useEffect() hook it's undefined. How can I only make the request once the props have been passed?

const user = useContext(UserContext);

const id = props.followerId;

useEffect(() => {
        axios
            .get(`http://localhost:3000/users/followers/${id})
            .then((res) => {
                if (res.status === 200) {
                    user.setFollower(res.data);
                }
            })
            .catch((err) => {
                console.log(err);
            });
    }
}, []);

CodePudding user response:

You can add id in dependency array so that if the id changes then the useEffect will run

and add a guard clause in useEffect so that request will only go if there is an id as:

const id = props.followerId;

useEffect(() => {
    if (id) {   // IF GUARD CLAUSE ONLY RUN IF ID IS SOMETHING
        axios
            .get(`http://localhost:3000/users/followers/${id}`)
            .then((res) => {
                if (res.status === 200) {
                    user.setFollower(res.data);
                }
            })
            .catch((err) => {
                console.log(err);
            });
    }
}, [id]);   // ADD ID IN DEPENDENCY ARRAY

CodePudding user response:

You need to add id as dependency in useEffect. Moreover, add a boolean check on id too.

const user = useContext(UserContext);

const id = props.followerId;

useEffect(() => {
!!id & & axios
            .get(`http://localhost:3000/users/followers/${id})
            .then((res) => {
                if (res.status === 200) {
                    user.setFollower(res.data);
                }
            })
            .catch((err) => {
                console.log(err);
            });
    }
}, [id]);

CodePudding user response:

useEffect with empty array means it only execute when component mount. if you use id in useEffetc dependency array then it will execute whenever id change its value and on mount also. so if id exist then call getFollower. like this

const user = useContext(UserContext);

const id = props.followerId;

useEffect(() => {
   const getFollower=(uid)=>{  
       axios.get(`http://localhost:3000/users/followers/${uid}`)
            .then((res) => {
                if (res.status === 200) {
                    user.setFollower(res.data);
                }
            })
            .catch((err) => {
                console.log(err);
            });
       }
   }

if(id) getFollower(id)
}, [id]);
  • Related