Why I have error when use Api from DummyJSON - reactjs

Run code and I get "Consider adding an error boundary to your tree to customize error handling behavior.: How can I fix it
import React, { useState, useEffect } from "react";
const BASE_URL = "https://dummyjson.com/products";
export default function App() {
const [product, setProduct] = useState([]);
useEffect(() => {
fetch(`${BASE_URL}`)
.then((res) => res.json())
.then((res) => {
setProduct(res);
})
// .then(console.log)
}, []);
return (
<ul>
{product.map((item) => (
<li key={item.id}>
{item.products.brand}
</li>
))}
</ul>
);
}
I tried change another API and it dose not have error

The problem is what type of data in file json. In this case data' type is object so I can not use map to render product.
first I change useState hook from empty array to object
const [product, setProduct] = useState({ products: [] });
then fetch data from api
const fetchData = () => {
fetch(`${BASE_URL}?limit=5`)
.then((res) => res.json())
.then((data) => {
setProduct(data);
});
};
useEffect(() => {
fetchData();
});
after fecth data and set to state I render it

Related

How to display data from Mongodb in React using Axios

I'm facing difficulty displaying data in React - Here is my code:
import Axios from 'axios';
import { useNavigate } from 'react-router';
export default function ProductCatalog() {
let navigate = useNavigate();
function addProduct() {
navigate('/adding')
}
const [products, setProducts] = useState([{}])
useEffect(() => {
const axiosProd = async () => {
const response = await Axios('http://localhost:3001/getProducts');
setProducts(response.data)
};
axiosProd();
}, []);
const useProducts = products.map((product)=>{
return <div>
<h1>{product.name}</h1>
</div>
})
return(
<>
<button className = "button" onClick={addProduct}>Add New Product</button>
<br></br>
{useProducts}
</>
)
}
I know data is coming in as JSON Objects as when i follow the link of http://localhost:3001/getProducts, I see my data. What am i doing wrong?
You should make a function then outside of the function call the use effect.
To do a get request using axios use axios.get(api)
For example:
// Get All Shoes
const getShoes = () => {
axios.get('/shoes')
.then(res => setShoes(res.data))
.catch(err => console.log(err));
}
Then
useEffect(() => {
getShoes();
}, [])

Issue with fetching data

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;

How do I map through an unnamed array in React?

I have an array that looks like this.
[{"id":19,"name":"asd","salary":123},{"id":20,"name":"wer","salary":1}]
But when I try to map through it in React I get an Error
Uncaught TypeError: data.map is not a function
import React, { Component, useState, useEffect } from 'react';
function EmployeeList() {
const [data, setData] = useState({ items : [] });
const getEmployees = () => {
fetch("http://127.0.0.1:8000/api/employee-list")
.then((response) => response.json())
.then((data) => {
setData(data);
console.log(data);
})
};
useEffect(() => {
getEmployees();
}, [])
return (
<div>
<ul>
{data.map((employee) =>
<li>{employee.name}</li>
)}
</ul>
</div>
)
export default EmployeeList;
That's because you are not setting data to an array, but an object at first. Use this instead:
const [data, setData] = useState([]);
This assumes that your data comes back from the API as you specified, i.e., as an array. If instead it comes back in the format suggested by your original initial value then you'd need to use:
{data && data.items && data.items.map((employee) =>

How to export const to other components react?

I created a file Category.js
import React, { useState } from 'react'
export const CategoryData = (props) => {
const [Category, setCategory] = useState('')
fetch('https://www.amrutras.com/Category.php')
.then((response) => response.json())
.then((responseJson) => {
{
setCategory(responseJson)
// responseJson.map((item) => Alert.alert(item.Name))
}
// Showing response message coming from server after inserting records.
})
.catch((error) => {
console.error(error)
})
return Category
}
export default CategoryData
I want to use this Category const in my other component.
I tried to do that with
import CategoryData from '../consts/CategoryData'
and using this function in useEffect of another component. like this.
useEffect(() => {
console.log(CategoryData)
})
But it's not working.
You cannot use hooks directly within functions, unless they are custom hooks which you then cannot invoke inside other hooks but have to follow the rules of hooks to use them
You can restructure your code to implement CategoryData like a custom hook
export const useCategoryData = (props) => {
const [Category, setCategory] = useState('')
useEffect(() => {
fetch('https://www.amrutras.com/Category.php')
.then((response) => response.json())
.then((responseJson) => {
{
setCategory(responseJson)
// responseJson.map((item) => Alert.alert(item.Name))
}
// Showing response message coming from server after inserting records.
})
.catch((error) => {
console.error(error)
})
}, [])
return Category
}
export default useCategoryData;
Now you can use it in your component like
function App () {
const categoryData = useCategoryData();
...
}
SOLUTION2:
Another way to implement this is to not use custom hook but implement a normal function like
export const CategoryData = (props) => {
return fetch('https://www.amrutras.com/Category.php')
.then((response) => response.json())
})
.catch((error) => {
console.error(error)
})
}
export default CategoryData
and use it like
function App () {
const [categoryData, setCategoryData] = useState(null);
useEffect(() => {
CategoryData.then(res => setCategoryData(res));
}, []); Make sure to provide a dependency list to your useEffect otherwise you will end up in a infinite loop
}
Make it as a custom hook
import React, { useState } from 'react'
export const useCategoryData = (props) => {
const [Category, setCategory] = useState('')
useEffect(()=>{
fetch('https://www.amrutras.com/Category.php')
.then((response) => response.json())
.then((responseJson) => {
{
setCategory(responseJson)
// responseJson.map((item) => Alert.alert(item.Name))
}
// Showing response message coming from server after inserting records.
})
.catch((error) => {
console.error(error)
})
},[])
return {Category}
}
import it like
import {useCategoryData} from '.......'
const {Category} = useCategoryData()

useEffect causing .map() error when sending post request

When I try adding a new post I get this error. But when I console.log({ newPost }) I see that the new obj gets added. Something is happening when I try setting it in setPost({ newPost }).
import React, { useState, useEffect } from "react"
import axios from "axios"
const Users = () => {
const [posts, setPosts] = useState([])
useEffect(() => {
const getPosts = async () => {
const { data: post } = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
)
setPosts(post)
}
getPosts()
}, [])
const handlePost = async () => {
const obj = {
title: "foo",
body: "bar",
userId: 1,
}
const { data: post } = await axios.post(
"https://jsonplaceholder.typicode.com/posts",
obj
)
const newPost = [post, ...posts]
setPosts({ newPost })
}
return (
<div>
<h1>List of all Posts</h1>
<button onClick={() => handlePost()}>Post new title</button>
<ul className="list-group list-group-flush">
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
)
}
export default Users
The error is that you are calling setPosts with an object when you mean it to be an array.
Replace
setPosts({ newPost })
With
setPosts( newPost )
This part doesn't really matter, but I would say that when dealing with async methods it's a better practice to setState with a function of the previousState rather than accessing the previous state directly.
setPosts((posts) => [post, ...posts])
posts state variable is expected to be an Array, so there's no need to set it inside an object. Change setPosts({ newPost }) to setPosts(newPost). It should work.
I run the code with the error in my pc so there are some errors.
But I changed setPosts(newPost).
So it is working very well.
If we avoid these errors, we should be familiar with React Hooks

Resources