no rendered data from endpoint reactjs - reactjs

I am building a project using Reactjs and ready endpoints to render the data from it.
I have been following this video tutorial
it was working fine until I got to render the data to the browser not only in the console
what am I doing wrong?
import {React, useEffect, useState} from 'react';
import axios from 'axios';
function App() {
const [isLoading, setIsLoading] = useState(true);
const [posts, setPosts] = useState({});
useEffect(() => {
getData();
}, []);
const getData = () => {
const ENDPOINT= "https://snetmyapp.herokuapp.com/case1";
axios (ENDPOINT)
.then((response: any) => {
setIsLoading(false);
console.log("RES",response.data);
if (response.data.posts) {
setPosts(response.data.posts)
}
else
console.log("No posts");
});
};
const data = isLoading ? (
<p>Loading...</p>
) : (
<div><pre>{JSON.stringify(posts, null, 2)}</pre></div>
);
return (
<div>{data}</div>
);
}
export default App;

It looks like there are no posts in returned data
offerList is returned instead.
Check out this sandbox

Related

Why does my image in Firebase Storage render only after reload 404 error

I am able to upload the image successfully to Firebase Storage, but when I try to render it back to my dashboard I get a 404 error, file not found. I figure it has to do with the database not uploading the image and then sending it back to my react app. When I reload the page, the image renders. I have an async/await function for setting the userImage. What is the best way to manage this? New to React btw.
import { useState, createContext, useEffect } from "react";
import app from "../firebase";
const UserContext = createContext();
const UserProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [userImg, setUserImage] = useState(null);
console.log("userImg from context", userImg);
const img = async () => {
const imgPath = await app.firebase
.storage()
.ref(`users/${user.uid}/profile.jpg`)
.getDownloadURL();
setUserImage(imgPath);
};
useEffect(() => {
if (user) img();
}, [user]);
useEffect(() => {
app.auth().onAuthStateChanged(setUser);
}, [user]);
return (
<UserContext.Provider value={[user, setUser, userImg, setUserImage]}>
{children}
</UserContext.Provider>
);
};
export { UserContext, UserProvider };
The problem with your code is that the component gets rendered before even the img is retrieved from the server.
So what you can do is have a loading state in your component and until the img isn't received back from the server set the loading state to true.
import { useState, createContext, useEffect } from "react";
import app from "../firebase";
const UserContext = createContext();
const UserProvider = ({ children }) => {
const [loading, setLoading] = useState(false) // <--------Loading state--------
const [user, setUser] = useState(null);
const [userImg, setUserImage] = useState(null);
console.log("userImg from context", userImg);
const img = async () => {
setLoading(true) // Setloading to true
const imgPath = await app.firebase
.storage()
.ref(`users/${user.uid}/profile.jpg`)
.getDownloadURL();
setUserImage(imgPath);
setLoading(false) // <--------setting loading to false after receiving the image-------
};
useEffect(() => {
if (user) img();
}, [user]);
useEffect(() => {
app.auth().onAuthStateChanged(setUser);
}, [user]);
if(loading) {
return (<div>Loading...</div>) // <-----return loading if loading is true----
}
return (
<UserContext.Provider value={[user, setUser, userImg, setUserImage]}>
{children}
</UserContext.Provider>
);
};
export { UserContext, UserProvider };

axios in react works locally but doesn't work in heroku

I used axios twice. onces on internal api in my express server, and once external api in react. Getting internal api from express to react works, but getting external api in react is not working
It does work locally but it's doing nothing when deployed in heroku
Below code is where getting api data doesn't work. Also I can't find any record of getting the data when I check the log in heroku
import React, { useState, useEffect } from "react";
import Axios from "axios";
export default function Weather() {
const [weather, setWeather] = useState("");
const [currentWeather, setCurrentWeather] = useState("");
const [feelsLike, setFeelsLiks] = useState("");
const [tempMax, setTempMax] = useState("");
const [tempMin, setTempMin] = useState("");
useEffect(() => {
Axios.get(
"http://api.openweathermap.org/data/2.5/weather?q=Seoul&appid=4a80048ac273c6f7e70908e2bb631fee"
).then((response) => {
setWeather(response.data.weather[0].main);
setCurrentWeather(Math.floor(response.data.main.temp - 273));
setFeelsLiks(Math.floor(response.data.main.feels_like - 273));
setTempMax(Math.floor(response.data.main.temp_max - 273));
setTempMin(Math.floor(response.data.main.temp_min - 273));
});
});
return (
<div>
<h3>Weather</h3>
<div id="displayWeather">
<p>{weather}</p>
<p>temp: {currentWeather}°</p>
<p>feels like: {feelsLike}°</p>
<p>Max temp: {tempMax}°</p>
<p>Min temp: {tempMin}°</p>
</div>
</div>
);
}
and below is where getting data works
import React, { useState, useEffect } from "react";
import Axios from "axios";
export default function News() {
const [recentNews, setRecentNews] = useState([]);
const [newsUrl, setNewsUrl] = useState([]);
useEffect(() => {
Axios.get("api/newsname").then((response) => {
setRecentNews(response.data);
});
Axios.get("/api/newsurl").then((response) => {
setNewsUrl(response.data);
});
});
const data = [];
for (let i = 0; i < recentNews.length; i++) {
data.push(<a href={newsUrl[i]}>{recentNews[i]}</a>);
}
return (
<div>
<h3>News</h3>
<div id="displayNews">
{data.map((element) => {
return <li className="list">{element}</li>;
})}
</div>
</div>
);
}

How do I properly set up an API call using useEffect?

Here is my entire component. In the console the correct data is showing up at "data" but when I try to run map on it it says "map is not a function." The 16 items in the console are the correct beaches.
import React, {useState, useEffect} from 'react';
import axios from 'axios';
export default function Beaches() {
const [data, setData] = useState({beaches: []})
// const [hasError, setErrors] = useState(false)
useEffect(() => {
const fetchBeaches = async () => {
const result = await axios('http://localhost:3000/beaches');
setData(result.data);}
fetchBeaches();
}, [])
console.log(data)
return (
<ul>
{data.beaches.map(beach => (
<button>{beach.name}</button>
))}
</ul>
)
}
Because you're not setting the beaches data in state correctly.
Replace useEffect code with this:
useEffect(() => {
const fetchBeaches = async () => {
const result = await axios('http://localhost:3000/beaches');
setData({beaches: result.data});
}
fetchBeaches();
}, [])
furthermore, you can improve the state structure of beaches data:
import React, { useState, useEffect } from "react";
import axios from "axios";
export default function Beaches() {
const [beaches, setBeaches] = useState([]);
// const [hasError, setErrors] = useState(false)
useEffect(() => {
const fetchBeaches = async () => {
const result = await axios("http://localhost:3000/beaches");
setBeaches(result.data);
};
fetchBeaches();
}, []);
return (
<ul>
{beaches.map((beach) => (
<button>{beach.name}</button>
))}
</ul>
);
}

Simple function that retrieves data from an API is not returning the data

I have this React component that used to return an HTML element like this:
const PartsList = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'https://localhost:44376/api/parts',
);
setData(result.data);
};
fetchData();
}, []);
return (
<>
{data.map((item, index) => (
<label key={index} className="inline">
<Field key={index} type="checkbox" name="machineParts" value={item.id} />
{item.name}
</label>
))}
</>
);
}
export default PartsList;
Now, I want it to return only an array of JSON, no HTML.
So I tried modifying the component so that it looks like this:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'https://localhost:44376/api/machines',
);
setData(result.data);
console.log("data as seen in function: ", JSON.stringify(result, null, 2));
};
fetchData();
}, []);
return data;
When I write it out to the console in this function, I see all the needed data.
But when I write it out to the console in the main App.js, I just see undefined.
What could I be doing wrong?
Thanks!
Originally you wanted a component because it had to render HTML.
Now what you actually need is to move everything out to a function.
So you can do this in your main App.js:
import React from 'react';
import axios from 'axios';
const fetchData = async () => {
const result = await axios(
'https://localhost:44376/api/machines',
);
return JSON.stringify(result, null, 2);
};
const App = () => {
const result = await fetchData()
console.log(result)
return <div>Main App<div>
}
export default App
This is how you make a function to return data that you can call to see the console result in your main App component.
This obviously just demonstrates the concept, you can take it further by moving that function out to its own file that you can import into your App.js folder.

Getting 'undefined' at component level

I am getting undefined when I run the code below. However, If I console.log the results within the hook, I get all the data
hook (works fine, fetches the data)
import { useState, useEffect } from 'react';
import axios from 'axios';
export const GetOrders = () => {
const [data, setData] = useState();
useEffect(() => {
axios.get('/allorders').then(res => {
setData(res.data);
});
}, []);
console.log(data);
return { data };
};
component (returns undefined when I log the data)
import React from 'react';
import { GetOrders } from '../hooks/orders';
export const AllOrders = () => {
const { data } = GetOrders();
console.log(data);
return (
<ul>
{data.forEach(order => (
<li>{order.status}</li>
))}
</ul>
);
};
Your code looks good. Just initialize data with [] value so it will not break when you will loop over values since undefined.map() will fail
const [data, setData] = useState([]);

Resources