This is my code to show the get request data in frontend
import React, { useEffect, useState } from "react";
import axios from "axios";
const Users = () => {
const [users, setusers] = useState({ collection: [] });
const [Error, setError] = useState();
useEffect(() => {
axios
.get("http://127.0.0.1:5000/users/users-list")
.then((response) => {
console.log(response.data);
// console.log(response.status);
// console.log(response.statusText);
// console.log(response.headers);
// console.log(response.config);
setusers({ collection: response.data });
return response.data;
})
.catch((error) => {
console.log({ Error: error });
setError(error);
// return error;
});
}, []);
return (
<div>
{users.collection.length > 0 &&
users.collection.map((element, i) => {
return (
<div key={i}>
{element.Name}‑{element.Email}
‑{element.Message}
</div>
);
})}
{Error && <h2>{Error}</h2>}
</div>
);
};
export default Users;
As you can see in the following code I am trying to display my get data in the browser web page .
but its is not displaying in the browser but showing in console.log()
First of all dont make variable starts with capital letter as you have used Error (which refers to Error class in JavaScript) in useState.
You can show component with different state as follows:
const [isLoading, setIsLoading] = useState(false);
const [users, setUsers] = useState([]);
const [error, setError] = useState("");
useEffect(() => {
setIsLoading(true);
axios.get("http://127.0.0.1:5000/users/users-list")
.then((res => {
setUsers(res.data);
setIsLoading(false);
})
.catch(err => {
setError(err.response.data);
setIsLoading(false);
}
},[]);
if (isLoading) {
return <LoadingComponent />
}
if (error !== "") {
return <h1>{error}</h1>
}
if (users.length < 1) {
return <h1>There is no user.</h1>
}
return <div>
{users.collection.map((element, i) => {
return (
<div key={i}>
{element.Name}‑{element.Email}
‑{element.Message}
</div>
);
})}
</div>
You implementation ok it's work with [{"Name":"T","Email":"t#email.com","Message":"T user"}] API response format. Just check what is API response in your end, It should render the results.
I have notice catch block you have to set error message instead of Err object
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const Users = () => {
const [users, setusers] = useState({ collection: [] });
const [Error, setError] = useState('');
useEffect(() => {
axios
.get('https://63a0075424d74f9fe82c476c.mockapi.io/api/collection/Test')
.then((response) => {
console.log(response.data);
// console.log(response.status);
// console.log(response.statusText);
// console.log(response.headers);
// console.log(response.config);
setusers({ collection: response.data });
})
.catch((error) => {
console.log({ Error: error });
setError('Something went wrong');
// return error;
});
}, []);
return (
<div>
{users.collection.length > 0 &&
users.collection.map((element, i) => {
return (
<div key={i}>
{element.Name}‑{element.Email}
‑{element.Message}
</div>
);
})}
{Error && <h2>{Error}</h2>}
</div>
);
};
export default Users;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I tested your code (with a different API) and could not find any issues. As you can see in the codesandbox, the values appear on the screen:
https://codesandbox.io/s/wonderful-ganguly-5ecbid?file=/src/App.js
I noticed that you capitalised the object properties, Name, Email and Message. Perhaps this caused you the issue. You will need to check the console logged object to see whether the properties are capitalised or not. Usually, they will not be. So you would call them like this: element.name, element.email and element.message.
I guess your response data is maybe your problem. I don't know what is your response but it must be array.
I have replace the axios url with some other fake urls and it worked. but remember that the user.collection must be array. Therefor, you need to make sure that response.data is array. Otherwise, you need to set response.data as array in user.collection.
import React, { useEffect, useState } from "react";
import axios from "axios";
const Users = () => {
const [users, setusers] = useState({ collection: [] });
const [Error, setError] = useState();
useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => {
console.log(response.data);
setusers({ collection: [response.data] });
return response.data;
})
.catch((error) => {
console.log({ Error: error });
setError(error);
// return error;
});
}, []);
return (
<div>
{users.collection.length > 0 &&
users.collection.map((element, i) => {
return <div key={i}>{element.title}</div>;
})}
{Error && <h2>{Error}</h2>}
</div>
);
};
export default Users;
Related
iam new to React and trying to show data from API,
It works at first but after reload i got error " Cannot read properties of undefined (reading 'length')",
any ideas what could it cause ?
thanks
code looks like this:
import React from "react";
import { useEffect, useState } from "react";
const options = {
//options for API call
};
const Ticket = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
fetch(
"https://daily-betting-tips.p.rapidapi.com/daily-betting-tip-api/items/daily_betting_coupons?sort=-id",
options
)
.then((res) => res.json())
.then((data) => {
setData(data);
})
.catch((err) => {
console.log(err);
})
.finally(() => {
setLoading(false);
});
}, []);
if (loading) {
return <p>data is loading...</p>;
}
return (
<div>
<h1>length: {data.data.length}</h1>
<h2></h2>
</div>
);
};
export default Ticket;
You are getting this error because you have data state which is an array but in return you are trying to access data key from the state's data array, which is not there hence it returns the undefined and then you are trying to access the length from undefined.
Instead of data.data.length just use data.length
Use this code. I edited your code. Add a condition when set your data variable
if(data.data) {
setData(data.data)
}
And also change this line
<h1>length: {data.data.length}</h1>
To
<h1>length: {data.length}</h1>
Here is the full code
import React from "react";
import { useEffect, useState } from "react";
const options = {
//options for API call
};
const Ticket = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
fetch(
"https://daily-betting-tips.p.rapidapi.com/daily-betting-tip-api/items/daily_betting_coupons?sort=-id",
options
)
.then((res) => res.json())
.then((data) => {
if (data.data) {
setData(data.data);
}
})
.catch((err) => {
console.log(err);
})
.finally(() => {
setLoading(false);
});
}, []);
if (loading) {
return <p>data is loading...</p>;
}
return (
<div>
<h1>length: {data.length}</h1>
<h2>Hello world</h2>
</div>
);
};
export default Ticket;
i have my json received from api call and is saved in the state "data"
i want to show a loading screen while api is being fetched like i have a state for that too "Loading"
Loading ? Then render data on elements : Loading..
const App = () => {
const [data, setData] = useState([]);
const [Loading, setLoading] = useState(false);
useEffect(() => {
Fetchapi();
}, []);
const Fetchapi = async () => {
try {
await axios.get("http://localhost:8081/api").then((response) => {
const allData = response.data;
setData(allData);
});
setLoading(true);
} catch (e) {
console.log(e);
}
};
return (
<div>
i need my json object rendered here i tried map method on data and i am
getting errors and i have my json2ts interfaces imported in this
</div>
);
};
export default App;
I would camelCase your values/functions and move your fetchApi into the effect itself, as currently its a dependency.
Put setLoading(true) above your fetch request as currently it's not activating until the fetch goes through.
Then below it put setLoading(false), and also inside of your catch.
In your return statement you can now add something like this:
<div>
{loading ? "Loading..." : JSON.stringify(data)}
</div>
Edit
Example for the commented requests.
import { Clan } from "../clan.jsx"
// App
<div>
{loading ? "Loading..." : <Clan data={data}/>}
</div>
// New file clan.jsx
export const Clan = (props) => {
return (
<div>
<h1>{props.data.clan.name}</h1>
</div>
);
}
try this
interface ResponseData {
id: string
// other data ...
}
const App = () => {
const [data, setData] = useState<ResponseData | null>(null)
const [Loading, setLoading] = useState(true)
useEffect(() => {
Fetchapi()
}, [])
const Fetchapi = async () => {
try {
setLoading(true) // USE BEFORE FETCH
await axios.get("http://localhost:8081/api").then(response => {
setLoading(false) // SET LOADING FALSE AFTER GETTING DATA
const allData: ResponseData = response.data
setData(allData)
})
} catch (e) {
setLoading(false) // ALSO SET LOADING FALSE IF ERROR
console.log(e)
}
}
if (Loading) return <p>Loading...</p>
if (data?.length)
return (
<div>
{data.map(d => (
<div key={d.id}>{d.id}</div>
))}
</div>
)
return <div>no data found</div>
}
export default App
I am trying to display the data from an API in the UI. I can see the data in the console but I always get an error when I'm trying to map through the data in the return. Ideally I would like to access all the objects that is in the results array.
Here is the code of the App.js and a codesandbox if you want to test it.
import React, { useState, useEffect } from "react";
export function App() {
const [data, setData] = useState({
results: []
});
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const api = "https://apis.is/earthquake/is";
useEffect(() => {
//if (!api) return;
setLoading(true);
fetch(api)
.then((response) => response.json())
.then(setData)
.then(() => setLoading(false))
.catch(setError);
}, []);
if (loading) return <h1>Loading...</h1>;
if (error) return <pre>{JSON.stringify(error, null, 2)}</pre>;
if (!data) return null;
//{JSON.stringify(data)}
console.log(data);
console.log(data.results[1]);
if (data.results) {
return (
<div>
{data.results.map((i) => (
<li key={i.results}> {i.humanReadableLocation}</li>
))}{" "}
</div>
);
}
return <div> Failed to get data </div>;
}
The export default is missing
import "./styles.css";
import React, {
useState,
useEffect
} from "react";
export default function App() {
const [data, setData] = useState({
results: []
});
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const api = "https://apis.is/earthquake/is";
useEffect(() => {
//if (!api) return;
setLoading(true);
fetch(api)
.then((response) => response.json())
.then(setData)
.then(() => setLoading(false))
.catch(setError);
}, []);
if (loading) return <h1 > Loading... < /h1>;
if (error) return <pre > {
JSON.stringify(error, null, 2)
} < /pre>;
if (!data) return null;
//{JSON.stringify(data)}
console.log(data);
console.log(data.results[1]);
if (data.results) {
return ( <
div >
<
p > virka plíssss < /p> {data.results.map((i) => (
<li key={i.results}> {i.humanReadableLocation}</li>
))} <
/div>
);
}
return <div > Oops, náðist ekki að sækja gögn < /div>;
}
Updated code sanbox
What are you even trying to output? The results is an object. Here is a sample, but you need to decide what property you want in the LI, the key should probably not be an Object, pick a property.
{data.results.map((i) => (
<li key={i.results}> {i.timestamp}</li>
))}
Having done the necessary to read the data using fetchAPI, I am having problems displaying the content because of the nature of the array.
import React, { useState, useEffect } from "react";
function Home() {
const [userData, setUserData] = useState([]);
async function getData() {
let response = await fetch("https://api.xxxxxxxx.io/something/students");
let data = await response.json();
return data;
}
//call getData function
getData().then((data) => console.log(data)); //
useEffect(() => {
getData()
.then((data) => {
setUserData(data);
})
.catch((error) => {
console.log(error);
});
}, []);
return (
<div>
{Object.keys(userData).map((item, index) => (
<div key={index}>{item}</div>
))}
</div>
);
}
export default Home;
When I checked the console, the data are displayed but it is only showing students with no other data displayed.
I have the data below.
Try the following changes:
const [userData, setUserData] = useState({ students: [] });
...
return (
<div>
{userData.students.map((item, index) => (
<div key={index}>{item}</div>
))}
</div>
);
I am trying to pull data from an Axios Get. The backend is working with another page which is a React component.
In a function however, it doesn't work. The length of the array is not three as it is supposed to be and the contents are empty.
I made sure to await for the axios call to finish but I am not sure what is happening.
import React, { useState, useEffect } from "react";
import { Container } from "#material-ui/core";
import ParticlesBg from "particles-bg";
import "../utils/collagestyles.css";
import { ReactPhotoCollage } from "react-photo-collage";
import NavMenu from "./Menu";
import { useRecoilValue } from "recoil";
import { activeDogAtom } from "./atoms";
import axios from "axios";
var setting = {
width: "300px",
height: ["250px", "170px"],
layout: [1, 3],
photos: [],
showNumOfRemainingPhotos: true,
};
const Collages = () => {
var doggies = [];
//const [dogs, setData] = useState({ dogs: [] });
const dog = useRecoilValue(activeDogAtom);
const getPets = async () => {
try {
const response = await axios.get("/getpets");
doggies = response.data;
//setData(response.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
};
useEffect(() => {
const fetchData = async () => {
getPets();
};
fetchData();
}, []);
return (
<>
<NavMenu />
<ParticlesBg type="circle" margin="20px" bg={true} />
<br></br>
<div>
{doggies.length === 0 ? (
<div>Loading...</div>
) : (
doggies.map((e, i) => {
return <div key={i}>{e.name}</div>;
})
)}
</div>
<Container align="center">
<p> The length of dogs is {doggies.length} </p>
<h1>Knight's Kennel</h1>
<h2> The value of dog is {dog}</h2>
<h2>
Breeders of high quality AKC Miniature Schnauzers in Rhode Island
</h2>
<section>
<ReactPhotoCollage {...setting} />
</section>
</Container>
</>
);
};
export default Collages;
Try doing the following:
const [dogs, setData] = useState([]);
[...]
const getPets = async () => {
try {
const response = await axios.get("/getpets");
doggies = response.data;
setData(response.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
};
const fetchData = async () => {
getPets();
};
useEffect(() => {
fetchData();
}, []);
No idea if it will actually work, but give it a try if you haven't.
If you don't use useState hook to change the array, it won't update on render, so you will only see an empty array on debug.
As far as I can tell you do not return anything from the getPets() function.
Make use of the useState Function to save your doggies entries:
let [doggies, setDoggies ] = useState([]);
const getPets = async () => {
try {
const response = await axios.get("/getpets");
return response.data;
} catch (err) {
// Handle Error Here
console.error(err);
}
return []
};
useEffect(() => {
setDoggies(await getPets());
});
I used setState inside the getPets function. Now it works.
const Collages = () => {
const [dogs, setData] = useState([]);
const dog = useRecoilValue(activeDogAtom);
const getPets = async () => {
try {
const response = await axios.get("/getpets");
setData(response.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
};
useEffect(() => {
const fetchData = async () => {
getPets();
};
fetchData();
}, []);