Home > Software design >  react child component not re-rendering after state change
react child component not re-rendering after state change

Time:07-11

I have a child component that uses a value of the parent component as the state in the child component that value is fetched using API so the first time that value is none and after the response is fetched the value gets updated but after the first render when the value is none the app gets crashed and a white screen stuck and does not re-render.

my parent component

export default function Profile() {
  const [user, setUser] = useState({});
  const PF = process.env.REACT_APP_PUBLIC_FOLDER;
  const username = useParams().username;

  useEffect(() => {
    const fetchUser = async () => {
      try {
        const res = await axios.get(
          `http://localhost:8000/api/users?username=`   username
        );
        setUser(res.data);
      } catch (e) {
        console.log(e);
      }
    };
    fetchUser();
  }, [username]);
return <>
             <child user={user} />
</>

child component

export default function Rightbar({ user }) {
  const [followed, setFollowed] = useState(user.includes(user?.id))
  useEffect(() => {
},[user])
return(
//component
)
}

I am getting undefined in include.

CodePudding user response:

when we make a Http call to update the state we need to make try {} , catch {} to verify that the getted data is not undefined and not equal to none , with this test condition we will sure that our app will not crashed when he goes to update the state .

CodePudding user response:

In your case, the child component renders before the HTTP request is completed and the user is not set to data yet. You can refactor your code to something like the below:

export default function Rightbar({ user }) {

//const [followed, setFollowed] = useState(user.includes(user?.id))
useEffect(() => 
{

}, [user])


let followed = false;

if(user && user.id)
{
     followed = true;
}



return (<>{followed}</>);

}

Or you you can wait the HTTP call to completed and render the child component:

export default function Profile() {
const [user, setUser] = useState({});
const PF = process.env.REACT_APP_PUBLIC_FOLDER;
const username = useParams().username;

useEffect(() => {
  const fetchUser = async () => {
    try {
      const res = await axios.get(
        `http://localhost:8000/api/users?username=`   username
      );
      setUser(res.data);
    } catch (e) {
      console.log(e);
    }
  };
  fetchUser();
}, [username]);
return (<>
{user && <child user={user} />}
</>);

}
  • Related