Difficulties with useEffect and asyncawait - reactjs

I've read several questions here regarding my current difficulty; they also told me the way I was coding it was wrong, and I changed it. However, even after changing I still can't seem to get the proper result.
I'm trying to make a small React HTTP Request app for learning purposes. According to the classes I've been following, I managed to create the json server, setup to watch for the DB.json properly, etc. Now, inside the App.js I'm trying to make the async\await call for listing the products in the console.
First, I had the following error:
"Effect callbacks are synchronous to prevent race conditions. Put the async function inside:"
I fixed it by changing my code. It was triggering a warning and I found out the classes I've been following are a bit outdate. No problem. However, even after changing it I can't view the products I create on db.json. If I go to localhost:3000/products it shows up there (which means things are working).
I believe I'm doing it the right way now, but I still can't seem to figure out why I can't view the data.
Any input is appreciated. Thanks!
ps: I'm just starting with react.
App.Js
import './App.css';
import { useState, useEffect } from "react";
const url="http:/localhost:3000/products";
function App() {
const [products, setProducts] = useState ([]);
useEffect(() => {
const fetchData = async () => {
const data = await fetch(url);
console.log("Data:" + data)
const res = await data.json();
console.log("Res:" + res)
setProducts(res);
}
fetchData();
}, []);
console.log(products);
return (
<div className="App">
<h1>LIsta de produtos</h1>
</div>
);
}
export default App;

The URL you put is missing a "/", Check if the URL is right, rest else seems to be correct, the code below should work.
import "./App.css";
import { useState, useEffect } from "react";
// URL is probably wrong, this is fixed URL
const url = "http://localhost:3000/products";
function App() {
const [products, setProducts] = useState([]);
useEffect(() => {
const fetchData = async () => {
const data = await fetch(url);
console.log("Data:" + data);
const res = await data.json();
console.log("Res:" + res);
setProducts(res);
};
fetchData();
}, []);
console.log(products);
return (
<div className="App">
<h1>LIsta de produtos</h1>
</div>
);
}
export default App;

Related

Trying to use isPending in React 18 without Suspense and not getting expected results

I understand that the isPending return in React 18 is used so that lower priority state updates can happen last. I'm struggling to figure out how to make isPending work in a simple REST GET call example. I'm trying to write the code below without having to use a separate isLoading type state.
Is there anything I can do to make this happen? That is, with only isPending render a "loading..." message until the data has been retrieved?
(the results I get from the code below is I see a flash of "loading", then immediately see [] followed by my data. I want to see "loading" until my data actually loads)
import axios from "axios";
import { useEffect, useState, useTransition } from "react";
export default function Test1() {
const [data, setData] = useState([])
const [isPending, startTransition] = useTransition();
useEffect(() => {
async function fetchMyAPI() {
startTransition(async () => {
const results = await axios.get("/api/rest");
setData(results.data);
})
}
fetchMyAPI()
}, [])
if (isPending) return <div>Loading...</div>
return (
<div>{JSON.stringify(data)}</div>
);
}

How to populate my const before the page renders?

I'm pretty new to ReactJS dev and today i'm trying to get some data from an API using Axios. My issue is :
I'm trying to de map function on resultData to get what i want inside, but an error is proped and it's showing : resultData.map is not a function
If i comment this part of the code and just render the page first, then uncomment, it works and data are shown.
I'm assuming that data is not loaded before the rendering process is over so that's why i get this. But how to make it load before ?
Here my code snippets :
import React, { useState, useEffect } from "react";
import "./App.css";
import axios from "axios";
const Url = "someAPi";
function App() {
const [baseData, setBaseData] = useState({});
const [resultData, setResultData] = useState({});
useEffect(() => {
getBaseDataWithAxios();
}, []);
const getBaseDataWithAxios = async () => {
const response = await axios.get(Url);
setBaseData(response.data);
};
useEffect(() => {
getResultDataWithAxios();
}, []);
const getResultDataWithAxios = async () => {
const response = await axios.get(Url);
setResultData(response.data.result);
};
const listItems =
resultData.map((d) => <li key={d.value}>{d.value}</li>);
return (
<div className="App">
<header className="App-header">
<h2>generated fees</h2>
</header>
<div className="info-container">
<h5 className="info-item">{baseData.status}</h5>
<h5 className="info-item">{baseData.message}</h5>
<h5 className="info-item">{listItems[1]}</h5>
</div>
</div>
);
}
export default App;
The error is thrown on this :
const listItems =
resultData.map((d) => <li key={d.value}>{d.value}</li>);
I know my data can be read since if i comment the listItems and the displaying part in the return, render the page, uncomment everything, it displays the data properly.
Can someone explain to me how to populate data first ? During my research i've seen that this can happen by using Axios.
Thanks a lot !
The useEffect hook always runs after your component function returns in the render cycle.
Try an empty array for your initial value of resultData instead of an empty object:
const [resultData, setResultData] = useState([]);
There is no map built-in method on non-array objects, so during the first execution, you receive that error.

Error, when trying to change state with useState - Identifier expected. 'true' is a reserved word that cannot be used here.ts(1359)

I have been working with React for already 1 month and I am also using the hook useState(). But today I experienced such a weird error, which says, that I can't use "true" as a setState value. I use this hook very often, but this is the first time when nothing happens. The error, which is showing, is following:
Identifier expected. 'true' is a reserved word that cannot be used here.ts(1359)
It shows up, when I write setLoading(true) inside fetchTours function and the true is not accepted.
This is my code -
import React, { useState, useEffect } from 'react'
import Loading from './Loading'
import Tours from './Tours'
const url = 'https://course-api.com/react-tours-project'
function App() {
const [loading, setLoading] = useState(true)
const [tours, setTours] = useState([])
const fetchTours = async () = {
setLoading(true);
const response = await fetch(url);
}
if(loading){
return (
<main>
<Loading />
</main>
);
}
return (
<main>
<Tours />
</main>
)
}
export default App
What could the problem be?
I believe you have a syntax error, need a fat arrow. Like this:
const fetchTours = async () => {
setLoading(true);
const response = await fetch(url);
}

useEffect dependency array causing infinite loop [duplicate]

This question already has answers here:
Understanding the React Hooks 'exhaustive-deps' lint rule
(2 answers)
Closed 1 year ago.
I'm getting the following warning in the console:
Line 19:6: React Hook useEffect has a missing dependency: 'data'. Either include it or remove the dependency array and res.data is an empty array when I console log it.
But when I pass in data to the dependency array, I do get the correct API response in the console, but I get an infinite loop.
From what I've read, this is one of the most common traps to fall into when using useEffect, but I still have a hard time wrapping my head around how to resolve this or finding an answer I can truly understand.
Any help would be appreciated in what is currently wrong with my code, and how to resolve.
import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
const apiKey = process.env.REACT_APP_NASA_KEY;
const NasaPhoto = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const res = await axios(
`https://api.nasa.gov/planetary/apod?api_key=${apiKey}`
);
setData(res.data);
console.log(data);
};
fetchData();
}, []);
return (
<div>
<Link to='/'>Return Home</Link>
<h1>Nasa Data</h1>
</div>
);
};
export default NasaPhoto;
write your fetch data method outside the useEffect and call it in the useEffect then pass it as a dependency
your code should now be something like this
`
const fetchData = async () => {
const res = await axios(
https://api.nasa.gov/planetary/apod?api_key=${apiKey}
);
setData(res.data);
console.log(data);
};
useEffect(() => {
fetchData();
}, [fetchData]);
`

ReactJS: How to fetch data from API on button click

I am making an app to fetch data from a recipeDB API, and right now I need to click on the search button have it console.log some data. Right now it is giving me a network error when attempting to fetch the resource. I have my code setup like this
import React, { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
const API_ID = "0fc98505";
const API_KEY = "5e81ce76845f459b53f9fbe775e81e53";
const [recipes, setRecipes] = useState([]);
const getRecipes = async () => {
const response = await fetch(
`https://api.edamam.com/search?q=chicken&app_id=${API_ID}&app_key=${API_KEY}`
);
const data = await response.json();
setRecipes(data)
console.log(data);
};
return (
<div className="App">
<button onClick={getRecipes}>Retrive data</button>
</div>
);
}
If there is a network error, this means that your request is executed. I think the error here lies in your APP_ID and API_KEY. Another reason might be CORS. For more details visit MDN page.
Also you can check out «Network» tab in your developer tools(F12) where error description is sometimes shown in response body.

Resources