Search code examples
reactjsreact-props

How can I pass fetched data between components?


I am fetching some data in my App component and mapping through it to display names. I also have a counter component which besides the counts, I want to render the user names from the data fetched in App. I wish to know how do I pass the data's user names as props to the counter component so that it displays the names there as well?

Here is my App:

function App() {
  const {data, isLoading} = useAsync({promiseFn: loadUsers})
  if (isLoading)
    return "Loading..."
  if (data)

    return (<div className="container">
      {
        data.map(user => (
          <div key={user.username} className="row">
            <div class="col-md-8">
              <div class="card-body">
                <h2>{user.name}</h2>  // Need this to also display in button component
                <Counter id={user.name}/>
              </div>

My Counter Component's return :

  return (
    <div>
      <b>Would you like to work with (user.name data from app) </b> &nbsp; <i onClick={handleIncrement} class="far fa-thumbs-up" style={clickStyle}> Yes!</i>
      <br/>
      <h><b>{count}</b> have said Yes!</h>
    </div>
  );
}


Solution

  • In your App component you're sending the user's name as id into Counter.When you're sending a variable from parent component into another one, you can access it via props in child component. Also you need to pass props into child components. In addition You should change the user.name to props.id. Based on your code which you have attached in stackbiltz. Here's the correct code:

    function Likes(props) {
      const [count, setCount] = useState(0);
      const KEY = `count-${props.id}`;
      const clickStyle = {
        color: '#2197ba',
        cursor: 'pointer'
      };
    
      useEffect(() => {
        const parsedCount = Number(localStorage.getItem(KEY) || 0);
        setCount(parsedCount);
      }, []);
    
      useEffect(() => {
        localStorage.setItem(KEY, count);
      }, [count]);
    
      const handleIncrement = () => {
        setCount(prevCount => prevCount + 1);
      };
    
      return (
        <div>
          <b>Would you like to work with counter {props.id} </b> &nbsp;{' '}
          <i onClick={handleIncrement} class="far fa-thumbs-up" style={clickStyle}>
            {' '}
            Yes!
          </i>
          <br />
          <h>
            <b>{count}</b> have said Yes!
          </h>
        </div>
      );
    }
    

    Please refer to this document for more information about props: https://reactjs.org/docs/components-and-props.html