how to map multiple nested arrays json react rails api - reactjs

I have multiple nested arrays, how can I map them ? I could map only one nested with the help of #Apostolos
`
function RequestDetail({match}) {
const [request, setRequests] = useState({ user: {} });
const [fulfillment, setFulfillments] = useState({});
const [text, setText] = useState([]);
useEffect(() => {
fetchRequest();
}, []);
const fetchRequest = () => {
axios
.get(
`${baseUrl}/${match.params.id}`
)
.then((res) => {
setRequests(res.data);
console.log(res.data);
})
.catch((err) => console.log(err));
};
const handleSubmit = async (e) => {
//e.preventDefault();
const newfulfillment = {text}
try{
const response = await axios.post(`${baseUrl}/${match.params.id}/fulfillments`, newfulfillment);
setAuthHeaders();
const allFullfilments = [...fulfillment, response.data];
setFulfillments(allFullfilments);
setText('');
} catch (err) {
console.log(`Error: ${err.message}`);
}
}
`
The array I need is fulfillments

Your response is an array which contains another array fullfilments and you
u want an array with all fullfilments right?
To do so, you need to map your response, and retrieve your fullfilments, you'll have an "array of array" which you can .flat()
Something like
response.data.map(({fullfilments}) => fullfilments).flat()

Since I was using rails API, with the help of Serializers I could I get the needed data in a different way.

Related

React (Map , Axios , useState) add usestae new value using map with axios

here is a usestate so I want to add more customers using map
useEffect(() => {
getApiDAta()
async function getApiDAta() {
try {
const response = await axios.get('http://localhost:5000/custumer/')
.then(res => {setcustName(res.data)
custName.map((items) => {
setSuggestions([items.firstname])
console.log(suggestions);
})
})
} catch (error) {
console.error(error);
}
}
},[]);
const [custName,setcustName] = useState([])
const [suggestions,setSuggestions] = useState(
custName.map((items) => {
return [`${items.name}`];
})
);
i want to multiple item in suggestions so please help me
You are trying to map an empty array. Try to map it after its filled:
custName.map((items) => {
return [`${items.name}`];
})

Problem occur when use array of objects in filter function React

I try to get data from the backend and view data in the frontend. To do this I try this code.
function ViewPost() {
const { postId } = useParams();
console.log(postId);
const [posts, setPosts] = useState({});
useEffect(() => {
getOnePost();
}, []);
const getOnePost = async () => {
try {
const response = await axios.get(`/buyerGetOnePost/${postId}`);
console.log(response);
const allPost = response.data.onePost;
setPosts(allPost);
} catch (error) {
console.error(`Error: ${error}`);
}
};
console.log(posts);
console.log(posts.wasteItemList);
const [offers, getOffers] = useState([]);
useEffect(() => {
getAllOffers();
}, []);
const getAllOffers = async () => {
await axios
.get(`/viewPendingSellerOffers`)
.then((response) => {
const allNotes = response.data.existingOffers;
getOffers(allNotes);
})
.catch((error) => console.error(`Error: ${error}`));
};
console.log(offers);
const wasteItem = offers?.filter(
(wasteItem) =>
wasteItem.status === "accepted" &&
wasteItem.wasteItemsListId === posts?.wasteItemList?._id,
);
console.log(wasteItem);
}
I call the first API and get a specific post data and this post has an array of objects called wasteItemList. When I use this code console.log(posts.wasteItemList), I get length 2 array of objects. This is an image of this result.
Then I call the second API and get length 8 array of objects. This is an image of this result.
Then I try to filter data using this code const wasteItem = offers?.filter(wasteItem => wasteItem.status==='accepted' && wasteItem.wasteItemsListId===posts?.wasteItemList?._id). But this filter function give an empty array. What is the reason for this problem? How do I solve this?
As I mentioned in the comments, your naming seems a little off. A function that supposedly gets one post assigns to a state atom that's plural, and your setter for offers is getOffers.
Here's a simplification/rewrite of your component that assumes post is supposed to be singular and offers is in plural. Also, you were missing the data dependency postId for the useEffect.
In addition, since wasteItem is singular, I assume you want the first matching offer, not all of them, so .find() is the thing.
function ViewPost() {
const { postId } = useParams();
const [post, setPost] = useState(undefined);
const [offers, setOffers] = useState(undefined);
useEffect(() => {
setPost(undefined);
axios
.get(`/buyerGetOnePost/${postId}`)
.then((resp) => setPost(resp.data.onePost))
.catch((err) => console.error(err));
}, [postId]);
useEffect(() => {
axios
.get(`/viewPendingSellerOffers`)
.then((response) => setOffers(response.data.existingOffers))
.catch((err) => console.error(err));
}, []);
if (post === undefined || offers === undefined) {
return <>Loading...</>;
}
const wasteItem = offers.find(
(wasteItem) =>
wasteItem.status === "accepted" &&
wasteItem.wasteItemsListId === post.wasteItemList?._id,
);
return (
<div>
<div>Post: {JSON.stringify(post)}</div>
<div>Offers: {JSON.stringify(offers)}</div>
<div>Waste Item: {JSON.stringify(wasteItem)}</div>
</div>
);
}

Get an empty array when use array of objects in filter function React

I am new to react and try to get data from the database and view data in frontend. This is the code I tried.
function ViewPost() {
const { postId } = useParams();
console.log(postId);
const [post, setPost] = useState({});
useEffect(()=>{
getOnePost();
}, []);
useEffect(()=>{
if (post && post.location) {
console.log(post.location);
console.log(post.location.longitude);
console.log(post.location.latitude);
}
}, [post]);
const getOnePost = async () => {
try {
const response = await axios.get(`/buyerGetOnePost/${postId}`)
console.log(response);
const allPost=response.data.onePost;
setPost(allPost);
} catch (error) {
console.error(`Error: ${error}`)
}
}
console.log(post);
console.log(post.wasteItemList);
const [offers, setOffers] = useState([]);
useEffect(()=>{
getAllOffers();
}, []);
const getAllOffers = async () => {
await axios.get(`/viewPendingSellerOffers`)
.then ((response)=>{
const allNotes=response.data.existingOffers;
setOffers(allNotes);
})
.catch(error=>console.error(`Error: ${error}`));
}
console.log(offers);
const wasteItem = offers?.filter(wasteItems => wasteItems.status==='accepted' && wasteItems.wasteItemsListId===post?.wasteItemList?._id);
console.log(wasteItem);
}
When I call the first API I get these results. This is an image of results.
In the above image, there is a length 2 array of objects called as wasteItemList. Then I call the second API and get these results.
This image shows length 8 array of objects. Then I try to filter the data of these two arrays using this const wasteItem = offers?.filter(wasteItems => wasteItems.status === 'accepted' && wasteItems.wasteItemsListId === post?.wasteItemList?._id); code. But I get a length 0 empty array as the results of this filter function. But when I try an ID of a wasteItemList array
6112679258125b0418844368 instead of using this post?.wasteItemList?._id code I get the correct result. What is the problem here? How do I solve this problem?
Edited code:
function ViewPost() {
const { postId } = useParams();
const [post, setPost] = useState(undefined);
const [offers, setOffers] = useState(undefined);
useEffect(() => {
setPost(undefined);
axios
.get(`/buyerGetOnePost/${postId}`)
.then((resp) => setPost(resp.data.onePost))
.catch((err) => console.error(err));
}, [postId]);
useEffect(() => {
axios
.get(`/viewPendingSellerOffers`)
.then((response) => setOffers(response.data.existingOffers))
.catch((err) => console.error(err));
}, []);
useEffect(()=>{
if (post && post.location) {
console.log(post.location);
console.log(post.location.longitude);
console.log(post.location.latitude);
}
}, [post]);
console.log(post);
console.log(post?.wasteItemList);
console.log(offers);
const wasteItem = offers?.filter(wasteItems => wasteItems.status==='accepted' && wasteItems.wasteItemsListId===post?.wasteItemList?._id);
console.log(wasteItem);
}
useEffect runs asynchronously so your post will not be available
on your getAllOffers function which is located in your second
useEffect.
You will need to make your getOnePost() and getAllOffers() to
run synchronously within a single useEffect.
Or the problem is in your condition checks as I can't tell much only
by your given array picture.

How to assign data to a variable from axios get() response

I am trying to use Express (axios) to build a React app.
I was able to get an array of objects from MongoDB using get() method. Currently the list is printed out to the console. How can I assign it to a variable so that I could use that array for further actions?
useEffect(() => {
const expensesListResp = async () => {
await axios.get('http://localhost:4000/app/expenseslist')
.then(
response => console.log(response.data))
}
expensesListResp();
}, []);
Many thanks!
You can assign it in the following way, let say you have an array posts:
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get('url')
.then(res => setPosts(res.data))
.catch(err => console.log(err));
}, [])
In your code, you can do it in this way:
const [resultArray, setResultArray] = useState([]);
useEffect(() => {
const expensesListResp = async () => {
await axios.get('http://localhost:4000/app/expenseslist')
.then(
response => setResultArray(response.data))
}
expensesListResp();
}, []);
I am assuming that you have data printed on the console.log(response.data) and you want it to be assigned to a variable so that you can use it right?
if that's the case you are already using async function just name it with whatever variable name you want it to be before await.
for example:
const expensesListResp = async () => {
const "your variable name" = await axios.get('http://localhost:4000/app/expenseslist')
}
you can also save that variable in your state, if you want to use that variable data throughout your application.

React Native - state is returning null after setting state

I'm very much new to react native currently i'm building small app for just getting an idea about this. I'm facing an issue in mapping the data from API. This is the json response returning from the api
{"data":[{"digit":300,"countsum":"52"},{"digit":301,"countsum":"102"},{"digit":302,"countsum":"27"},{"digit":303,"countsum":"201"},{"digit":500,"countsum":"101"}]}
When i tried to map this data i'm facing some issues. I stored the response from API to the state and when i tried to display the state data using map function it's showing the state value is null. This the code i tried till now
const [listdata, setListData] = useState(null)
useEffect(() => {
// Run! Like go get some data from an API.
getListData();
}, []);
const getListData = async () => {
const token = await AsyncStorage.getItem("#userToken")
axios
.get(constants.BASE_URL + "getlist?token=" +token)
.then(response => setListData(response.data))
.catch(error => {
console.log(error);
});
listdata.map(item => <Text>{item.digit}</Text>)
}
Do it like this,
export default function ComponentName () {
const [listdata, setListData] = useState([])
useEffect(() => {
// Run! Like go get some data from an API.
getListData();
}, []);
const getListData = async () => {
const token = await AsyncStorage.getItem("#userToken")
axios
.get(constants.BASE_URL + "getlist?token=" +token)
.then(response => setListData(response.data))
.catch(error => {
console.log(error);
});
}
return (<>
listdata.map(item => <Text>{item.digit}</Text>)
</>
);
}
You have to wait the fetch execution and later do the list map.
// wait for it
await axios
.get(constants.BASE_URL + "getlist?token=" +token)
.then(response => setListData(response.data))
.catch(error => {
console.log(error);
});
listdata.map(item => <Text>{item.digit}</Text>)
If you want to map the data then do that inside return statement of your code ,like:
return(
{listData?listdata.map(item => return <Text>{item.digit}</Text>):""}
);
This is a sample of a meant in my comment above:
Try console.log listdata at this stage, you will find that it is still
null, in other words, the value of the updated value of the
listdata:useSate will be ready after the render take place. You can
make another function outside of the current one. then use useEffect
with listdata to update your text views
const [listdata, setListData] = useState(null)
useEffect(() => makeRemoteRequest(), [listdata])
makeRemoteRequest = () => {
const url = `your-url-of-data-here`;
fetch(url)
.then(res => res.json())
.then(res => {
setListData(res.data);
})
.catch(error => {
console.log(error)
});
};
You could try the following:
const [listdata, setListData] = useState([])
useEffect(() => {
// Run! Like go get some data from an API.
getListData();
}, []);
const getListData = async () => {
const token = await AsyncStorage.getItem("#userToken")
try {
const dataResponse = await axios.get(constants.BASE_URL + "getlist?token=" +token);
setListData(dataResponse.data || [] );
} catch(error) {
console.log(error);
}
}
return (<>
listdata.map(item => <Text>{item.digit}</Text>)
</>);

Resources