1

How can I make an API call (possibly async) to fetch data to be able to use it further. The class does not render anything by itself.

I am new to functional components and am trying to - fetch data in AppForm and - send it over as an argument to fun2().

Any suggestions are greatly appreciated. Code snippets would be even more helpful. Thanks in advance.

const AppForm = ({ x, y, z, id, ...props }) => (

  <InnerForm
    input={x ? fun1(x) : fun2()}
    isEqual={(a, b) => (a && a.id) === (b && b.id)}
  >

    {val => (
      <MainForm
        x={x}
        y={y}
        z={z}
        initialValues={val}
        {...props}
      />
    )}
  </InnerForm>
);
AppForm.propTypes = {
x: PropTypes.object,
y: PropTypes.object,
z: PropTypes.object,
}
vv1129
  • 37
  • 1
  • 1
  • 6
  • Does this answer your question? https://reactjs.org/docs/hooks-effect.html – keikai Feb 21 '20 at 04:31
  • I did have a look at useEffect(). I am not sure how to use it in my project as I have another class embedded and do not having a render(). Any suggestions would help. Thanks! – vv1129 Feb 21 '20 at 04:35

1 Answers1

1

With useEffect my react hooks, you can make an api call and set the data in state using useState hook. Once data is received you can render the component by passing in the required values

const AppForm = ({ x, y, z, id, ...props }) => {
    const [data, setData] = useState(null);

    useEffect(() => {
        axios.get('path').then((res) => setData(res));
    }, []);

    if(!data) return <Loading />
    return (
      <InnerForm
        input={x ? fun1(x) : fun2(data)}
        isEqual={(a, b) => (a && a.id) === (b && b.id)}
      >

        {val => (
          <MainForm
            x={x}
            y={y}
            z={z}
            initialValues={val}
            {...props}
          />
        )}
      </InnerForm>
    )

};
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Thank you for the suggestion. I tried it, but have some issues with the syntax on the very first line `const AppForm = ({ x, y, z, id, ...props }) => {` . The error reads **TypeError: Object(...) is not a function** . I am mostly having a hard time figure out the syntax for a class like this. – vv1129 Feb 21 '20 at 05:07
  • You are using React v16.8 or higher right? If not, we would need to use class pattern to implement the above logic. – Shubham Khatri Feb 21 '20 at 05:24
  • Thank you very much. I had v16.2 and upgrading it did the trick. Thanks again! – vv1129 Feb 21 '20 at 14:09