So I have made a custom hook for fetching and I’m trying to use that hook and filter some stuff from it using my params. But the fetch returns undefined firstly which actually breaks my code.
Custom Hook code
import axios from "axios";
import { useState, useEffect } from "react"
export const useFetch = (url) => {
const [loading, setLoading] = useState(false);
const [data, setData] = useState([]);
const [error, setError] = useState('')
const getData = () => {
setLoading(true)
try {
axios.get(url)
.then(response => {
setData(response.data);
setLoading(false)
})
} catch (error) {
setError(error)
}
};
useEffect(() => {
getData()
}, [url])
return {loading, data, error}
}
Code where I’m trying to use the fetch
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useFetch } from '../custom_hooks/useFetch';
const PersonDetails = () => {
const { loading, data , error } = useFetch('https://randomuser.me/api?results=20');
const { results } = data;
const { id } = useParams();
const [person, setPerson] = useState({})
useEffect(() => {
const newPerson = results?.find(person => parseInt(person.login.uuid) === parseInt(id))
console.log(newPerson)
setPerson(newPerson)
}, [])
return (
<div>
Testing
</div>
)
}
export default PersonDetails