Home > Enterprise >  How can I fetch data out of a component, using useParams in React.js?
How can I fetch data out of a component, using useParams in React.js?

Time:03-30

I had a issue with my API call with React. When I fetch data directly inside the component, it works very well, using this code :

export default function WeightFollowUp() {
   const {userId} = useParams()
   const [statistics, setStatistics] = useState(null)


  useEffect(()=>{
    async function fetchActivityData() {
      try{
        const response = await fetch (`http://localhost:3000/user/${userId}/activity`)
        const results = await response.json()
        setStatistics(results.data.sessions)
      }
      catch(err){
        console.log(err)
      }
      finally{
        console.log("Fetch completed")
      }
    }
    fetchActivityData()
  }, [])

Then I want to import the fetchActivityData fonction from an other file in order to get all my futur API calls in the same place. So it becomes this code :

  useEffect(()=>{
    fetchActivityData()
  }, [])

With this second version, the consol show an error message as follow :

ReferenceError: userId is not defined
    at fetchActivityData (APIcall.jsx:3:1)

Is there an other solution to solve this issue, keeping in mind that fetching data out of the component is mendatory for this project. ??

I tried to put the useParams in my APIcall file but useParams is only working inside the component.

Thank you guys for your help.

CodePudding user response:

When you create your fetchActivityData function just pass two parameters userId and setStatistics, something like that:

async function fetchActivityData(userId, setStatistics) {
  try{
    const response = await fetch (`http://localhost:3000/user/${userId}/activity`)
    const results = await response.json()
    setStatistics(results.data.sessions)
  }
  catch(err){
    console.log(err)
  }
  finally{
    console.log("Fetch completed")
  }
}

And when you call into your WeightFollowUp component just pass argument userId and setStatistics for change your state.

useEffect(()=>{
  fetchActivityData(userId, setStatistics)
}, [])
  • Related