fetch the api data and put it inside the tables - javascript

I am trying to fetch the api data and put it inside the tables, now i am using mock data
so I was able to write successfully actions and reducers.
now I am able to call the api.
but in the network call I am not see response in the api and seeing blocked response content status.
I am using react hooks for react and redux.
this is where I am making the api call
useEffect(() => {
getPosts(channel);
}, []);
can you tell me how to fix it.
providing my code snippet and sandbox below.
https://codesandbox.io/s/material-demo-kpt5i
demo.js
const channel = useSelector(state => state.channel);
const dispatch = useDispatch();
const getPosts = channel => dispatch(fetchPosts(channel));
useEffect(() => {
getPosts(channel);
}, []);
actions.js
export function fetchPosts(channel) {
return function(dispatch) {
dispatch(requestPosts());
return fetch(`http://jsonplaceholder.typicode.com/users`)
.then(
response => response.json(),
error => console.log("An error occurred.", error)
)
.then(json => {
dispatch(receivedPosts(json));
});
};
}

according to your sample on codesandbox, it is due to you are loading from https site but your source is from http. change http://jsonplaceholder.typicode.com/users to https://jsonplaceholder.typicode.com/users will solve your issue.

Related

Making two requests in useEffect

I am trying to fetch some user data from Firebase using getDoc and some data from MongoDB using axios in React.js.
Code:
async function getSolvedProblems() {
const docRef = await doc(db, "users-progress", user.uid);
await getDoc(docRef).then((doc) => {
console.log(doc.data());
});
}
useEffect(() => {
//fetch user's solved problems from firebase
getSolvedProblems();
//fetch problems from db server
axios
.get(process.env.REACT_APP_BACKEND_URL)
.then((res) => {
//doing something here
})
.catch((err) => {
console.log(err);
});
}, []);
But I don't know why the firebase data is not getting logged in console, when I hit refresh. But when I make any change in code, and save it, then it gets logged. I am unable to understand how useEffect is working here.
This is use effect work on below:
useEffect(() => {
//Runs only on the first render
}, []);
Also, you need to handle the catch block in your getSolvedProblems() method, see is there any error there.
On my guess, there is no value on user.uid when you load on page render

React Prop returning Null as it relies on state

Hopefully a simply one.
I make an API call in my component which brings down some account information such as AccountUid, Category etc, i use state to set these.
useEffect(() => {
fetch(feed_url, {
headers: {
//Headers for avoiding CORS Error and Auth Token in a secure payload
"Access-Control-Allow-Origin": "*",
Authorization: process.env.REACT_APP_AUTH_TOKEN,
},
})
//Return JSON if the Response is recieved
.then((response) => {
if (response.ok) {
return response.json();
}
throw response;
})
//Set the Account Name state to the JSON data recieved
.then((accountDetails) => {
setAccountDetails(accountDetails);
console.log(accountDetails.accounts[0].accountUid);
console.log(accountDetails.accounts[0].defaultCategory);
})
//Log and Error Message if there is an issue in the Request
.catch((error) => {
console.error("Error fetching Transaction data: ", error);
});
}, [feed_url]);
This Works perfectly well and it Logs the correct values in my .then when testing it.
The issue however is that i want to pass these down as props. But i get an error that they are being returned as null (My default state).. i presume as they're jumping ahead.
<div className="App">
<GetAccountName
accountUID={accountDetails.accounts[0].accountUID}
defCategory={accountDetails.accounts[0].defaultCategory}
/>
</div>
How do i pass the the 2 details im logging as props?? I've tried setting default state to "" instead of null and just get that it is undefined.
If you dont want to use conditional render in your child component, so you should try optional chaining
<GetAccountName
accountUID={accountDetails?.accounts?.[0]?.accountUID}
defCategory={accountDetails?.accounts?.[0]?.defaultCategory}
/>
Since fetching is asyncronous, the most common way is to show some loading indicator (like a spinner) & once the data come in, show the component instead.
If you don't need an indicator, you might just return null.
The general idea is to manipulate some intermediary states (e.g. data, isError) based on the promise state.
Check out react-query library example or a lighter abstraction like useFetch hook to see how they manage it.
Here's a sample implementation of useFetch taken from this article:
const useFetch = (url, options) => {
const [response, setResponse] = React.useState(null);
const [error, setError] = React.useState(null);
const [abort, setAbort] = React.useState(() => {});
React.useEffect(() => {
const fetchData = async () => {
try {
const abortController = new AbortController();
const signal = abortController.signal;
setAbort(abortController.abort);
const res = await fetch(url, {...options, signal});
const json = await res.json();
setResponse(json);
} catch (error) {
setError(error);
}
};
fetchData();
return () => {
abort();
}
}, []);
return { response, error, abort };
};

Why does JavaScript render data from the useEffect() hook but fails to render the data when put in the function body?

I have a JSON file called teams.json that contains the basic structure ("name", "age", "country", "role", "team", and "image") in an object. I'm using React to use the function fetch() to retrieve the data from the local JSON file. When I call the useEffect (shown below) hook, the data is retrieved from the local JSON file and I'm able call a useState function to store the data in a state variable called data.
useEffect() function call
//file path
filePath = "/src/public/teams.json"
const getData = (file) => {
fetch(file)
.then(res => res.json())
.then(data => setData(data))
.catch(err => console.log("Error fetching data", err)
}
useEffect(() => {
getData(filePath)
}, [filePath])
If I try to edit or access data within the useEffect() hook, the data is able to be retrieved without any problems, as such.
.then(data => console.log(data[0]))
This returns a json object that contains the necessary information.
{
"name":"R",
"image":"https://example.com",
"team":"B",
"role":"WB",
"country":"American",
"age":18
}
However, in the main body of my react App, if I try to obtain data from the data state, it gives me an error saying Cannot read properties of undefined, shown below.
Body of React App
return (
<main>
{data[0].country}
</main>
)
But I get this error:
I've tried solutions to previous forums from:
Stack Overflow Discussion Axios
Stack Overflow Discussion Error Axios
I've moved my project to the structure:
-src
--public
*some files*
and put the JSON file in the public folder. It reads it now but still doesn't render. I've also tried using axios but to no avail.
If this is an easy fix, sorry about that! Thanks for your help!
Because the data isn't loaded yet.
Assuming your app is something like
function App() {
const [data, setData] = React.useState();
const getData = (file) => {
fetch(file)
.then((res) => res.json())
.then((data) => setData(data))
.catch((err) => console.log("Error fetching data", err));
};
useEffect(() => {
getData(filePath);
}, [filePath]);
return <main>{data[0].country}</main>;
}
you're starting off with an undefined data.
Add a guard against that:
if(!data) return <>Loading...</>;
return <main>{data[0].country}</main>;

Axios is not getting response on first load

I am new in React JS and trying to get the data inside useEffect and I have a separate function for my api, but when I check the data.next in console.log there is no data in the first load but after adding few changes it works fine but still has an error when I refresh the page. Also, I noticed when I tried to console.log inside of function where the Axios or api declared, there's already a data in the first load of an application. Did anyone encounter this issue? Or my approach is wrong?
Here are my codes
/src/App.js
useEffect(async () => {
const res = await service.apiPokemon.fetchAll();
console.log(res.data.next)
}, []);
/src/api/pokemon.js
import axios from 'axios';
const URL = 'https://pokeapi.co/api/v2/pokemon';
export const fetchAll = async () => {
try {
const res = await axios.get(URL);
console.log(res.data.next);
return res;
} catch (error) {
console.log(error);
};
};
This is a very common problem. Your content is loaded before fetching the data. To solve this, you can add a condition to not render your content until you get the data:
let [pokemonsList, setPokemonsList] = useState([])
// Your useEffect hook to fetch data on mount
return (
{ pokemonsList.lenght > 0 && // If you are sure you'll receive pokemons
<div> {pokemonList.map((pokemon) => (
<p> {pokemon.name} </p>
)} </div>
}
)
Now, you'll only see the names of the pokemons when you have the list.
You can also add a loading message in case the response takes time with Redux and selectors.

Different results from JSON data when retrieved in React app

I am trying to retrieve some data from an API in my react app. When I view the endpoint in FireFox there is an value _embedded, which is what I need, but when I access that endpoint in the react app, it is not there:
Firefox, viewing /wp-json/wp/v2/product?per_page=100&_embed :
When i view the endpoint via console.log in Inspector, viewing /wp/v2/product?per_page=100&_embed :
Is there something that I am missing?
Update:
I am using the following in React:
const Component = ({ state, actions }) => {
const [products, setProducts] = useState([]);
useEffect(() => {
fetch(state.source.api + "/wp/v2/product?per_page=100&_embed")
.then((response) => response.json())
.then((data) => {
setProducts(data);
});
}, []);

Categories

Resources