I am trying to fetch data from an API which requires access_token
. There is another API for fetching access_token
. So, I am first trying to fetch acess_token and then pass it to the API which returns data.
I observed that the token API is getting hit but by the time it is passed to the data API, token is undefined
Here is my code
const useFetch = (url, headers) => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(async () => {
const response = await fetch(url, headers)
const data = await response.json()
console.log(data)
setData(data)
setLoading(false)
},[]);
return {data, loading};
}
export default function CreateTestcaseStep2() {
var access_token_headers={
method : 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body : 'grant_type=something&client_id=something-test&client_secret=something&scope=something'
}
const {token, loading_token} = useFetch('ACCESS_TOKEN_API', access_token_headers)
console.log("token is ", token) // TOKEN IS PRINTED AS UNDEFINED HERE
var api_headers={ method: 'GET',
headers: {'Authorization': `Bearer ${token.access_token}`},
}
const {data, loading} = useFetch('DATA_API', api_headers)
}
Please suggest how to get access_token first and then pass it to data_api.
Top comments (0)