using React hooks in hierarchy

319 views Asked by At

I am new in react and have developed quite few functional components in my new react app that are getting called in loops. One of child component, renders radio button. On selecting the option of radio button, I need to call webapi and update the state in parent App.js. I have been looking into hooks and not been able to use built-in so far, thinking of implementing a custom hook. Can you please suggest the best approach

1

There are 1 answers

0
Ansh Saini On

Well, custom hooks are based on the hooks provided by react. Mostly useEffect and useState. I don't think you need more than that to call an API and update state in the parent component.

Here's the approach that is most common:

import React from "react";

export default function App() {
  const [data, setData] = React.useState([]);

  const onClick = () => {
    // Call API here and update state
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => {
        console.log(json);
        setData(json);
      });
  };

  return <Options onClick={onClick} data={data} />;
}

function Options({ data, onClick }) {
  return (
    <div>
      <h4>Data: </h4>
      <pre>{JSON.stringify(data, null, 2)}</pre>
      <input type="radio" onClick={onClick} />
    </div>
  );
}