How do I call JSON data stored as a variable in a different component?

Tags: , , , ,



I am currently drawing JSON data from my api using axios, and I am mapping this data and storing it as a variable. I want to be able to call these variables in my react components, but I can’t seem to figure out the best way.

Getting the JSON data and storing as a variable

function ProfileOne(){
  const [profiles, setProfiles] = useState([])

  useEffect(() => {
      axios.get("api/profiles/")
          .then(res =>{
              console.log(res)
              setProfiles(res.data)
          })
          .catch(err => {
              console.log(err)
          })
  }, [])
  return (
                  profiles.map(profile => {
                    const { name } = profile;
                    })
            <div>
                <h2><b>{profile.name}</b></h2>
            </div>

  )
}

And I want to be able to call something like profile.major in a react component, but the way I am currently trying to do it does not work. Please let me know the correct way to do this. Thank you in advance.

Answer

If you’re going to pass data from component to component you may have to restructure your application or implement a state management library such as redux. Personally I would move your API call to a parent component and then pass the data as props to child components. Something like the following for the parent component:

function ParentComponent() {

const [profiles, setProfiles] = useState([])

useEffect(() => {
  axios.get("api/profiles/")
      .then(res =>{
          console.log(res)
          setProfiles(res.data)
      })
      .catch(err => {
          console.log(err)
      })
   }, [])

return (
    <>
      <ProfileOne profiles={profiles} />
      <OtherComponent profiles={profiles} />
    </>
    );
}

And in the child component:

function ProfileOne(props){

    return props.profiles.map(profile => (
                   <div>
                       <h2><b>{profile.name}</b></h2>
                   </div>
               )
}


Source: stackoverflow