Runtime error after page refresh when doing an api call - reactjs

I have a web3 application that I am trying to view NFTs on a certain page and everything works when I route to it via links, or go back. But on page refresh I receive a runtime error that seems to indicate that there is improper data being passed but all objects being passed are defined properly
const { account } = useAccount();
const [NFTList, setNFTList] = useState([])
const [imageList, setImageList] = useState([])
const [tokenIDList, setTokenIDList] = useState([])
ConnectContract()
const getOwnedNFTs = useCallback(async () => {
const web3 = createAlchemyWeb3(
`https://polygon-mumbai.g.alchemy.com/v2/${process.env.NEXT_PUBLIC_ALCH_KEY}`,
);
const nfts = await web3.alchemy.getNfts({owner: account.data, contractAddresses: [ContractAddress]})
for (let i = 0; i < nfts.totalCount; i++) {
const response = await web3.alchemy.getNftMetadata({
contractAddress: ContractAddress,
tokenId: nfts.ownedNfts[i].id.tokenId
})
const image = await GetTokenImage(nfts.ownedNfts[i].id.tokenId)
setImageList(imageList => [...imageList, image])
setNFTList(NFTList => [...NFTList, response.metadata])
setTokenIDList(tokenIDList => [...tokenIDList, nfts.ownedNfts[i].id.tokenId])
}
},[])
useEffect(() => {
getOwnedNFTs()
},[])
Error:
I narrowed down the problem to the nfts line. If I hard code an address for owner then refresh works fine
const nfts = await web3.alchemy.getNfts({owner: "", contractAddresses: [ContractAddress]})
I don't really understand why this is happening as account.data is properly defined after the page is refreshed
UPDATE: I didn't see it before but the GET request is returning 400 error The request for some reason is leaving out the owner key/value from the api request
https://polygon-mumbai.g.alchemy.com/<API_KEY>/v1/getNFTs/?contractAddresses%5B%5D=<CONTRACT_ADDRESS>

Related

fetch vs. axios - what is the difference in error handling?

I have an app where I'm updating the API URL via searchbox and hence displaying certain items based on their name. The name parameter is being updated via onChange event in the input and then useEffect re-renders the list of the items as it observes the URL.
If the name parameters does not match any items, the page should show that no data was found.
Now, the thing is, that the feature works when I'm using fetch API as even if there's 404 code status, the fetchedData state seems to still get updated with the object below:
fetch
and "no data found" can be displayed.
However, when I use axios, fetchedData keeps the latest displayable list of items and I'm not able to show the communicate. Here's what I see in the console:
enter image description here
const [fetchedData, setFetchedData] = useState('');
const [search, setSearch] = useState('');
const { info, results } = fetchedData;
const url = `https://rickandmortyapi.com/api/character/?name=${search}`;
// useEffect(() => {
// (async function () {
// try {
// const response = await axios.get(url);
// console.log(response.data);
// setFetchedData(response.data);
// } catch (err) {
// console.log(err);
// }
// })();
// }, [url]);
useEffect(() => {
(async function () {
const response = await fetch(url);
const data = await response.json();
console.log(data);
setFetchedData(data);
})();
}, [url]);
Does anyone have any idea what's behind it and how that mechanism can be implemented with axios? When working the axios way, I tried to set fetcheData state to null in case of error but this did not work.

react page doesnt render when getting the data back from server

react won't work when rendering the page, but when i changed code in the vscode (added a line of console or comment one line out), the page is rendered. or when page is not rendered. when i hit refresh. i can see some of my content but it won't render. the usestate doesnt seem like to successfully save the value
const ParkDetail = () => {
const [parkId, setParkId] = useState('')
const [park, setpark] = useState('')
const [areas, setAreas] = useState([])
const [ridesName, setridesName] = useState([])
const [rides, setrides] = useState([])
let { id } = useParams()
console.log(id)
useEffect(() => {
async function getPark() {
try {
await setParkId(id)
const res = await axios.get(`/parks/details/${parkId}`)
console.log(res)
const park1 = await res.data.park
console.log(park1)
await setpark(park1)
console.log(park)
await setAreas(park1.serviceAnimalRelief)
// await setridesName(park1.topRides)
// console.log(ridesName)
} catch (e) {
console.log(e.message)
}
}
getPark()
}, [parkId])
}
I believe the problem is you using the state as parameters in your get requests. Since state setter functions do not return promises, using await on them is basically of no use. You should rather use the variables that you obtain from the get requests directly. For example, use id instead of parkId and so on.

How to display custom Nextjs error page when api call fails?

I created a custom Nextjs error page that I would like to display when the api call fails. What is currently happening is even if the api call fails, it still displays the same page as a successful route. For example, I have a route that is companies/neimans that pulls data from an api to display certain text on the page. If I type, companies/neiman I want my custom error page to show, but it is displaying the same page as if going to companies/neimans just without the data coming from the api. I do get a 404 in the console when visiting a url that is invalid but it doesn't display the custom error page or the default next js 404 page.
In my file system I have a pages directory and inside that a directory called companies with a file [companydata].tsx and one called 404.tsx. [companydata].tsx is the page that dynamically displays information about the company from the api.
This is what my api call currently looks like:
export const getCompanies = async (routeData: string): Promise<Company> => {
const client = getApiClient();
const response = await client.get<Company>(`api/companies/${routeData}`);
if (response) {
return response.data;
}
return {} as Company;
In the [companydata].tsx, I tried to do a check if the object was empty to then redirect to companies/404 but doing so makes it always display the 404 page.
if (Object.keys(company).length === 0) {
return <Redirect to="/company/404"/>;
}
If I console.log the company, it is rendering multiple times. The first 6 times, it is an empty array so that would explain why the 404 page is always showing. The data doesn't come through until after the 6th render. I am not sure why that is.
I am calling getCompanies inside another function,
export const getData = async (companyName: string): Promise<[Company, Sales]> => {
if (companyName) {
return (await Promise.all([getCompanies(companyName), getSales()])) as [
Company,
Sales
];
}
return [{} as Company, {} as Sales];
};
I am calling getData inside a useEffect within [companydata].tsx.
const Company: NextPage = (): JSX.Element => {
const [selectedCompany, setSelectedCompany] = useState<Company>({} as Company);
const [salesAvailable, setSalesAvailable] = useState<boolean>(false);
const [sales, setSales] = useState<Sales>({} as Sales);
const router = useRouter();
const {companydata} = router.query;
useEffect(() => {
const init = async (companyName: string) => {
const [companyData, salesData] = await getData(companyName);
if (companyData) {
setSelectedCompany(companyData);
}
if (salesData) {
setSalesAvailable(true);
setSales(salesData);
} else {
setSalesAvailable(false);
}
}
};
init(companydata as string);
};
}, [companydata]);
// returning company page here
You currently do not have a method to check the status of the API call. There are four possible outcomes of most API calls - data, no data, error, and loading. You should add the status checks in your API calls
Below are two examples of how this can be achieved.
get companies hook
export const useGetCompanies = async (path: string) => {
const [data, setData] = useState<Company>();
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
try {
setError(false);
setLoading(true);
const client = getApiClient();
const response = await client.get(`api/companies/${path}`);
setData(response.data);
} catch (error) {
setError(true);
} finally {
setLoading(false);
}
return {data, error, loading};
};
Since your data isn't related you also do a generic API fetch call something like
export async function useFetchData<T>(path:string){
const [data, setData] = useState<T>();
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
try {
setError(false);
setLoading(true);
const client = getAPIClient();
const response = await client.get<{ data: T }>(path);
if(response) setData(response.data);
} catch (error) {
setError(true);
} finally {
setLoading(false);
}
return { data, error, loading };
};
Example use.
const Company = async () =>{
const { query } = useRouter();
const company = await useFetchData<Company>(`api/companies/${query.companydata}`);
const sales = await useFetchData<Sales>(`api/companies/${query.companydata}/sales`);
if (company.loading || sales.loading) return <p>Loading...</p>;
if (company.error || sales.error) return <p>Error or could show a not found</p>;
if (!company.data || !sales.data) return <Redirect to="/company/404"/>;
return "your page";
}
It would be best to render the data independently of each other on the page and do the if checks there. This is beneficial because you don't have to wait for both calls to complete before showing the page.
I'd create two separate components (company and sales) and place the corresponding API call in each.
Typically assigning empty objects ({} as Company or {} as Sales) to defined types is bad practice because it makes TS think the object's values are defined when they are not - defeating the purpose of using TS.
They should be left undefined, and there should be a check to see if they are defined.
Lastly, I can't test the code because I don't have access to the original code base so there might be bugs, but you should get a pretty good idea of what's happening.

Using getServerSideProps and useEffect in Next.js to fetch data causes duplicate requests

I use getServerSideProps to fetch the initial articles data like this:
export const getServerSideProps = async () => {
const url =
"https://conduit.productionready.io/api/articles?limit=10&offset=0";
const res = await fetch(url);
const resJson = await res.json();
return {
props: {
data: resJson.articles
}
};
};
I need to update articles when page changeļ¼Œso I have the codes below:
export default function IndexPage(props) {
const { data } = props;
const [articles, setArticles] = useState(data);
const [page, setPage] = useState(0);
useEffect(() => {
const fetchData = async (page) => {
const url = `https://conduit.productionready.io/api/articles?limit=10&offset=${page}`;
const res = await fetch(url);
const resJson = await res.json();
setArticles(resJson.articles);
};
fetchData(page);
}, [page]);
//....
}
Then the question comes:
When your request this page directly, getServerSideProps runs on server-side and fetchs articles. But on client-side, fetchData in the useEffects would also run to fech the same articles again, which is redundant and a bit duplicated.
When transition to the IndexPage from another page through client-side route, there are also two requests for the same articles data: one request is sent to run getServerSideProps on server-side, the other is sent by fetchData. Again, redundant request for same data.
The complete demo is here
I think this is not an unusual situtation. I have seached a lot, but unfortunately, I haven't found any appropriate solutions. Does anyone encounter the same situation or know the best practice to handle it ?

How To Have Multiple Axios inside UseEffect That Doesnt Turn Error?

I need 3 axios :
to detect token, so I know which user is logged in. This is so that I can have a "userid" that I can pass for my other axios endpoints
the list of orders : returns an array of all the order history of that user
the data of the user, such as first_name, last_name, email etc
here is how it looks like:
const cookies = new Cookies();
const token = cookies.get("jwtToken");
const [user_detail, setuser_detail] = useState({});
const [userid, setuserid] = useState(null);
const [refresh, setrefresh] = useState(false);
const [orderData, setorderData] = useState([]);
const [userData, setuserData] = useState({});
useEffect(() => {
axios
.get(`http://localhost:3001/auth/token/decode/${token}`)
.then((result) => {
setuser_detail(result.data.user_detail);
setuserid(result.data.user_detail.user_id);
setrefresh(!refresh);
});
}, []);
useEffect(() => {
axios
.get(`http://localhost:3001/users/orders/${userid}`)
.then((res) => {
setorderData(res.data);
})
.catch((err) => console.log(err));
axios.get(`http://localhost:3001/users/detail/${userid}`).then((res) => {
setuserData(res.data[0]);
});
}, [refresh]);
If there is only the useEffect for Token and Orders, it works fine. However when I added the 3rd (user details) useEffect, it doesn't seem to want to receive the response. It will show only if I saved my react file, and then (without restarting my npm start) add the 3rd useEffect. It works until I refresh it, and it returns "TypeError: Cannot read property 'first_name' of undefined". Which doesn't make sense because if I don't refresh it, the first_name can in fact be rendered. I am pretty confused.
Use a single useEffect for onComponentMount, and create an async function inside your useEffect to handle your axios calls.
useEffect(() => {
async callAxios() => {
const result = await axios.get(`${url_one}`)
const user_orders = await axios.get(`${url_two}`)
const user_details = await axios.get(`${url_three}`)
}
callAxios()
}, [])

Resources