Reputation: 6025
I'd like to pass data from an Axios req that is in a separate component to another component. I will explain more detailed with my code snippets.
In my doorsLayout.js I am making an Axios call to an address. And I am getting the data in res.
this.serverRequest = axios
.get('http://blablabla/locks')
.then(res => {
// Rerender state
this.setState({
res,
dataToDisplay: res.data.slice(0, numToDisplay || 5)
})
})
Then (in the same file) I am making a new component called doorsItem.js here:
const items = dataToDisplay.map(item => <DoorsItem item={item} />)
And inside of DoorsItem I am outputting the data from the Axios call:
const DoorsItem = ({ item }) =>
<Grid>
<Row key={item._id} className="show-grid">
<Col md={12}>
<ul style={{ marginTop: '10px' }}>
<li className="info-container">
<h4 className="title-text-container">{item.address.street}</h4>
{/*etc etc*/}
So I can output all of the information that I got from the Axios call with {item.helloStackOverflow}
. But in the same file I'd like to output other stuff too, but from a different Axios req.
<DropdownButton
title="Lägg till ny användare"
id="bg-nested-dropdown"
>
<MenuItem eventKey="1" style={{ marginLeft: '500px' }}>
{/*Different Axios data here!*/}
</MenuItem>
</DropdownButton>
And the data I want to output is found in this component: users.js
this.serverRequest = axios
.get('http://blablabla/customers') <-- Just a different endpoint
.then(res => {
// Rerender state
this.setState({
res,
dataToDisplay: res.data.slice(0, numToDisplay || 5),
})
})
And like in doorsItem.js I have the same type of layout in userItem.js:
const UsersItem = ({ item }) =>
<Row
key={item._id}
className="show-grid"
style={{ margin: '-15px 0 -15px 0' }}
>
<Col md={12}>
<ul style={{ marginTop: '10px' }}>
<li className="info-container">
<div>
<h5 className="title-text-container">{`${item.name} ${item.surname}`}</h5>
So here is my question. If I want to output the data from 'http://blablabla/customers'
in my doorsItem
what's the easiest and "best" way to do so? Because I played around a little and when I'm clicking the dropdown I only see one name, because that name is associated with an ID. But I just want to have a dropdown with all of the names from 'http://blablabla/customers'
.
Sorry if my question is messy! But thanks for reading!
Upvotes: 0
Views: 1601
Reputation: 36179
There are two things you could do:
Make container component which handles all of the requests, and passes data as props to children components.
Introduce shared store object, like Redux or MobX does.
Sometimes you'll want to move from Redux state to React state (when storing something in Redux gets awkward) or the other way around (when more components need to have access to some state that used to be local).
Realize in which situation you are in.
PS. I choose to store request data most of the times in shared Redux object.
Upvotes: 1