How to guarantee that data from 'fetch' is present - javascript

I am doing something like this, where I retrieve the data of a fund which contains an id, then I query the server again using the retrieved id to retrieve data from another table:
const [backendData, setBackendData] = useState({})
const [fundData, setFundData] = useState({})
useEffect(() => {
async function fetchFund(){
console.log("fetching fund...");
var query = getQueryVariable('fund');
await fetch(`http://localhost:24424/api/funds?fund=${query}`).then(
response => response.json()
).then(
data =>{
setBackendData(data);
}
)
}
async function fetchData(){
var fundId = backendData[0]?._id ?? "fundid";
await fetch(`http://localhost:24424/api/funds/data?id=${fundId}`).then(
response => response.json()
).then(
data =>{
setFundData(data);
}
)
}
fetchFund();
fetchData();
}, [])
The problem is that in the fetchData() function, fundId is always equal to the fallback value fundid when the page first loads, so the server query fails. When using {fundId} later on in the page, it works fine as the value is eventually retrieved. How can I tell React to wait for backendData[0]?._id to be present before executing the fetchData() function?

You should separate the two function so one depend of the existing of the other your code will look something like this
const [backendData, setBackendData] = useState({})
const [fundData, setFundData] = useState({})
useEffect(() => {
async function fetchFund(){
console.log("fetching fund...");
var query = getQueryVariable('fund');
await fetch(`http://localhost:24424/api/funds?fund=${query}`).then(
response => response.json()
).then(
data =>{
setBackendData(data);
}
)
}
fetchFund();
}, [])
useEffect(() => {
if(!backendData?.[0]?._id) return;
async function fetchData(){
var fundId = backendData[0]?._id ?? "fundid";
await fetch(`http://localhost:24424/api/funds/data?id=${fundId}`).then(
response => response.json()
).then(
data =>{
setFundData(data);
}
)
}
fetchData();
}, [backendData])
Now fetchData will only get called when at least one backendData is available

Related

Trying to console.log data within useEffect. Not logging any information

function UserAccounts() {
const [accounts, setAccounts] = useState();
useEffect(() => {
async function fetchAccounts() {
const res = await fetch(
'https://proton.api.atomicassets.io/atomicassets/v1/accounts'
);
const { accounts } = await res.json();
setAccounts(accounts);
console.log(accounts);
}
fetchAccounts();
}, []);
}
I'm trying to understand why console.log shows nothing in this example and what is the correct way to console.log the data that is being fetched from the api.
Well, you need to get the structure of the returned payload from the API correct. It does not have an accounts property.
The payload looks like this:
{
"success":true,
"data":[{"account":"joejerde","assets":"11933"},{"account":"protonpunks","assets":"9072"}],
"queryTime": 1646267075822
}
So you can rename the data property while destructuring. const { data: accountList } = await res.json();
function UserAccounts() {
const [accounts, setAccounts] = useState();
useEffect(() => {
async function fetchAccounts() {
const res = await fetch(
'https://proton.api.atomicassets.io/atomicassets/v1/accounts'
);
const { data: accountList } = await res.json();
setAccounts(accountList);
// logging both the state and the fetched value
console.log(accounts, accountList);
// accounts (state) will be undefined
// if the fetch was successful, accountList will be an array of accounts (as per the API payload)
}
fetchAccounts()
}, [])
return <div>
{JSON.stringify(accounts)}
</div>
}
Edit: using some other variable name while destructuring, confusing to use the same variable name as the state (accounts).
Working codesandbox
One thing I would change is working with try/catch surrounding async/await statements.
If your await statement fails it will never reach the console.log statement.
Unless you have another component handling those errors, I would use it in that way.
That is my suggestion:
function UserAccounts() {
const [accounts, setAccounts] = useState();
useEffect(() => {
try {
async function fetchAccounts() {
const res = await fetch(
'https://proton.api.atomicassets.io/atomicassets/v1/accounts'
);
const { accounts } = await res.json();
setAccounts(accounts);
console.log(accounts);
}
} catch (err) {
console.log(err)
// do something like throw your error
}
fetchAccounts();
}, []);
}
since state function runs asyncronousely . therefore when you use setAccounts it sets accounts variable in async way , so there is a preferred way of doing this thing is as below
problems i seen
1.fetch result should destructured with data instead of accounts variable
2.setAccounts function is running async way so it will not print result immedietly in next line
import { useEffect, useState } from "react";
export default function App() {
const [accounts, setAccounts] = useState();
async function fetchAccounts() {
const res = await fetch(
"https://proton.api.atomicassets.io/atomicassets/v1/accounts"
);
const { data } = await res.json();
setAccounts(data);
}
// on component mount / onload
useState(() => {
fetchAccounts();
}, []);
// on accounts state change
useEffect(() => {
console.log(accounts);
}, [accounts]);
return <div className="blankElement">hello world</div>;
}
check here sample

making api requests and response.json()

I have a question about api request and async await
For example, I have a function as such:
export const getTopStories = async () => {
const response = await instance.get(`/home.json?api-key=${api_key}`)
const data = response.json()
return data
}
is response.json() completely necessary here? I think I've also seen it where data is destructured immediately, for example,
export const getTopStories = async () => {
const {data} = await instance.get(`/home.json?api-key=${api_key}`)
return data
}
Does the second version work? Are they equivalent somehow?

Passing external data into components

In my react app, I am currently passing a list of stores by calling the API directly from the URL.
const getStore = async () => {
try {
const response = axios.get(
'http://localhost:3001/appointment-setup/storeList'
);
return response;
} catch (err) {
console.error(err);
return false;
}
};
I pass this function into my useEffect hook where I would set my get a list of stores using resp.data.stores:
const [storeLocations, setStoreLocations] = useState([]);
useEffect(() => {
async function getData(data) {
await service.stepLocation.init();
const resp = await getStore();
setStoreLocations(resp.data.stores);
}
setFlagRender(true);
return getData();
}, []);
This works, however, I noted in useEffect there is a call await service.stepLocation.init(). There is a file that already takes care of all the backend/data for the component.
const stepLocation = {
// removed code
// method to retrieve store list
retrieveStoreList: async function ()
let response = await axios.get(
constants.baseUrl + '/appointment-setup/storeList'
);
return response.data.stores;
,
// removed code
Since this data is available, I don't need the getStore function. However when I try to replace response.data.stores in useEffect with service.stepLocation.retrieveStoreList no data is returned. How do I correctly pass the data from this file in my useEffect hook?
I think your useEffect should be like follows as you want to save the stores in your state.
useEffect(() => {
const updateStoreLocations = async () => {
const storeLocations = await service.stepLocation.retrieveStoreList();
setStoreLocations(storeLocations);
}
updateStoreLocations();
}, [])

How to pass state from one useEffect to another useEffect on intial page load?

I have a component which displays products for a category. CategoryId is taken from subscribe method which is formed by pubsub pattern so I am waiting sub function to finish and passing to my API but it is not working on intial load of the page?
import { subscribe } from "./pubsub";
const Test = () => {
const [productId, setProductId] = useState({});
const [response, setResponse] = useState([]);
React.useEffect(() => {
function sub() {
return new Promise((resolve, reject) => {
subscribe("product-message", (data) => {
// console.log("Got some message", data);
// setProductId(data.productId);
resolve(data.productId);
});
});
}
async function fetchData() {
let message = await sub();
let response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${message.productId}` // Here I couldn't get the async data from above useEffect
);
console.log(response);
setResponse(response);
}
fetchData();
}, []);
return <div>{response.title}</div>; //It is not printing in intial load
};
export default Test;
So here is my sandbox link: https://codesandbox.io/s/happy-forest-to9pz?file=/src/test.jsx
If you only need the response, you do not need to store productId in state and then use it in another useEffeect to fetch data. You can simply implement the logic in one useEffec. Also note that you need to use the json response from fetch call so you need to use it like
let response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${productId}`
).then(res => res.json());
or
let res = await fetch(
`https://jsonplaceholder.typicode.com/todos/${productId}`
)
let response = await res.json();
Complete function will look like
const Test = () => {
const [response, setResponse] = useState([]);
React.useEffect(() => {
async function fetchData(productId) {
let response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${productId}`
).then(res => res.json());
console.log(response);
setResponse(response);
}
console.log("Api calls");
subscribe("product-message", (data) => {
// console.log("Got some message", data);
fetchData(data.productId);
});
}, []);
return <div>{response.title}</div>;
};
export default Test;
However if you need productId in your application, you can go via a multiple useEffect approach like you have tried in your sandbox. Also make sure that you are using thee fetch call correctly and also make sure to not make the API call wheen productId is not available
const Test = () => {
const [productId, setProductId] = useState({});
const [response, setResponse] = useState([]);
React.useEffect(() => {
console.log("Api calls");
subscribe("product-message", (data) => {
// console.log("Got some message", data);
setProductId(data.productId);
});
}, []);
React.useEffect(() => {
async function fetchData() {
const res = await fetch(
`https://jsonplaceholder.typicode.com/todos/${productId}` // Here I couldn't get the async data from above useEffect
);
const response = await res.json();
console.log(response);
setResponse(response);
}
if(productId) {
fetchData();
}
}, [productId]);
return <div>{response.title}</div>;
};
export default Test;
Working Sandbox

React state not updating after async await call

I am using React Hooks and the useEffect to get data from an API. I need to make 2 consecutive calls. If I console.log the response directly, it shows the correct response, but when I console.log the state, its empty and its not updating. What am I doing wrong?
const [describeFields, setDescribeFields] = useState([]);
useEffect(() => {
const fetchData = async () => {
await axios
.all([
axios.get("someUrl"),
axios.get("someotherUrl")
])
.then(
axios.spread((result1, result2) => {
console.log(result1.data.result.fields); //shows correct response
setDescribeFields(result1.data.result.fields);
console.log(describeFields); //shows empty array
})
);
};
fetchData();
}, []);
It will not be displayed just after that if you want to see latest changes just console log before return statement as setState is async your console.log run before then setState
const [describeFields, setDescribeFields] = useState([]);
useEffect(() => {
const fetchData = async () => {
await axios
.all([
axios.get("someUrl")
axios.get("someotherUrl")
])
.then(
axios.spread((result1, result2) => {
console.log(result1.data.result.fields); //shows correct response
setDescribeFields(result1.data.result.fields);
})
);
};
fetchData();
}, []);
console.log(describeFields); //Check here
return(
)
Note : [] array in useEffect means it will run only one time. If you want to update as long as variable changes then add it as dependency.
Here is working example : https://codesandbox.io/s/prod-thunder-et83o

Categories