0

I would want load new component after server response using React. Its could be a simple operation but something does not working at the moment. My code is the following:

const formSubmit = async e => {

  e.preventDefault();

  const response = await dataSubmit({
      toSend
  });

  if(response.status === 200){
    console.log("status 200");
     return(
        <>
          <ComponentPage />
        </>
     );
  }
  else{
    console.log("error status");
    return(
       <>
        <ComponentPage  />
       </>
    );
 }
}


async function dataSubmit(toSend) {
  
    return fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(toSend)
    })
      .then(data => (data.json()))

}

I tried removing e.preventDefault() or using effect but is not working. This component will have to ovverrife atually Form component shown. console.log lines works. How can I solve? Thanks

init
  • 55
  • 8

1 Answers1

1

returning a component as part of formSubmit or a clickHandler won't render the component.

the simplest way i can think of doing is to, make the render() or the default return of this component to be conditional.

have a loading state, set true when the form is submitted and false when you get the response. render your <Component/> only if loading is false.

something like this,

   const YourComponent = () => {
    const [loading, setLoading] = useState(false);
    
    //set loading when form is submitted.
    // unset it when the response is recieved.
    return <>
        {loading} ? <Loader/> : <Component/>
    </>
  }

you can extend the same principle to show errors as well.

Prasanna
  • 10,956
  • 2
  • 28
  • 40