简体   繁体   中英

use axios data fetch conditionally

I have a side pane component which can display different data depending on a button clicked.

I am using switch in function for that case, which is then rendered

const sidePaneComponent = (sidePane) => {    

  const renderSwitch = () => { 
    switch (sidePane.type) {
      case 'info':
          // here I want to fetch data
          return <> 

            {!data && <Loader />}
            {data && data.map(d => {
              return <div>{d.something}</div> 
            })}

          </>
      case 'otherCase':
          // here I do some calculations for example
          const number = 1+1;
          return <> 

            {number}

          </>
      ...
    }
  }

  ...

  return <> {renderSwitch()} </>

}

The issue I have is that if I use regular axios call, then when the data come, they are not rendered. If I want to use hooks like useEffect , they can't be called inside a function. Is there a solution for that?

EDIT: Just some of the cases in switch statement have the data fetch funcfionality

You should probably handle data fetching in a separate function and use conditional rendering to display the data if they are present or not:

const sidePaneComponent = () => {
  const [data, setData] = useState(null);

  const fetchData = async () => {
    switch (sidePane.type) {
      case 'info':
        const response = await axios.get('<your-url>');
        setData(response.data);
        break;
      ...
    }

    useEffect(() => {
        fetchData();
    }, [sidePane])

    return (
      <>
        {!data && <Loader />}
        {data &&
          data.map((d) => {
            return <div>{d.something}</div>;
          })}
      </>
    );
  };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM