I have a database as json file. During rendering I pick few objects at random and I want to update my global store when I map through the database, but calling dispatch in render() causes massive errors and I dont know how to proceed further.
Here is what I have without errors:
render() {
const fakePayload = this.props.fakePayload;
const rngPayloadId = Math.floor(Math.random() * 4);
const payload = fakePayload.map(payload => {
if (payload.payloadId === rngPayloadId) {
return payload.drugsId.map(id => {
return <tr>
<td> {id}</td>
<td>{drugs[id].name}</td>
<td><input value={undefined} type="number" name="price" /></td>
<td><button >Send</button></td>
<td><button>X</button></td>
</tr>
})
}
})
return (
<tbody>{payload}</tbody>
)
And what I would want to do is something like:
return payload.drugsId.map(id => {
this.props.dispatch(setId(randomNumber, id)
If it matters action looks like this:
export const setId = (id, drugId) => ({
type: 'SET_ID',
renderedDrugs: {
id,
drugId
}
})
What do I need to learn / do to do that?
Perhaps it is because you are dispatching an action in render. Have you tried dispatching the action on componentDidMount()?
Based on the comment:
constructor(props){
super(props);
this.state = {
rngId: 0
};
}
render(){
this.setState({rngId: Math.floor(Math.random() * 4)});
...
}
componentDidMount(){
this.props.dispatch(....);
}
Lifecycle events are a core part of React. You absolutely have to read up and understand it to a certain competency in order to use Redux. You cannot use an action inside render because an action updates your store, which updates the component, which calls render, which would also call your action, which updates your component, which calls render... I'm sure you see where this is going.
You are looking for either componentWillMount or componentDidMount. Functions inside these methods will be called once and will never call itself again while the component is mounted. Refer to the Facebook React docs on lifecycle events or other resources, like tutorials.
edit to answer your comment's question. A common paradigm for controlling rendering changes will the component is updated is to use a boolean (true/false) ternary statement, to show element or hide it (a simplification, but it works for now.) You'd be looking for something like this.
class SampleComponent {
constructor() {
this.state = {
show: false
}
}
componentDidMount() {
this.setState({show: true})
}
render() {
return (
<div>
{ this.state.show ? <div>mounted</div> : null }
</div>
)
}
There would be almost zero use cases to do something like this. componentDidMount occurs so quickly upon component mounting that you'd change this.state.show to true instantly. The html elements you were hiding using state would show as if they were never controlled with state to begin with.
Related
I have setInterval setup to be working properly inside componentDidMount but the parameters are not updated. For example, the text parameter is the same value as when the component initially mounted, despite being changed in the UI. I've confirmed text's value is correctly updated in Redux store but not being passed to this.retrieveData(text). I suspect the const { text } = this.props set the value in componentDidMount, which forbids it from updating despite it being different. How would I go about this issue?
Code below is an example, but my real use-case is retrieving data based on search criteria. Once the user changes those criteria, it will update with the new result. However, I'm unable to pass those new criteria into componentDidMount so the page would refresh automatically every few seconds.
class App extends React.Component {
componentDidMount() {
const { text } = this.props //Redux store prop
setInterval(() => this.retrieveData(text), 3000)
}
retrieveData = (text) => {
let res = axios.post('/search', { text })
updateResults(res.data) //Redux action
}
render() {
const { text, results } = this.props
return (
<input text onChange={(e) => updateText(e.target.value)} />
<div>
{results.map((item) => <p>{item}</p>}
</div>
)
}
}
Because you are using componentDidMount and setTimeout methods your retrieveData is called only once with initial value of the text. If you would like to do it in your current way please use componentDidUpdate method which will be called each time the props or state has changed. You can find more information about lifecycle here https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/.
If you would like to use setInterval just like in the question, you just need to access props inside of retrieveData method instead of using an argument.
retrieveData = () => {
let res = post("/search", { text: this.props.text });
updateResults(res); //Redux action
};
You can find working example for both cases here https://codesandbox.io/s/charming-blackburn-khiim?file=/src/index.js
The best solution for async calls would be to use some kind of middleware like https://github.com/reduxjs/redux-thunk or https://redux-saga.js.org/.
You have also small issue with input, it should be:
<input type="text" value={text} onChange={(e) => updateText(e.target.value)} />
Source Code
This Works
const { id, title, complete, updated_at } = todoItem
...
todoItems[todoItemIndex].title = title
todoItems[todoItemIndex].complete = complete
todoItems[todoItemIndex].updated_at = updated_at
this.setState({ todoItems })
This Doesn't Work
todoItems[todoItemIndex] = todoItem
this.setState({ todoItems })
or
todoItems[todoItemIndex] = { ...todoItem }
this.setState({ todoItems })
or
this.setState(state => {
todoItems: state.todoItems.map(item => {
if (item.id === todoItem.id) {
item = { ...todoItem }
}
return item
})
})
Other Notes
I call componentDidUpdate() to confirm that this.state.todoItems is actually being updated when I use todoItems[todoItemIndex] = { ...todoItem }.
componentDidUpdate() {
console.log(this.state.todoItems)
}
always update your state in immutable way, so the current solution and the other to options are not valid.
the problem with your last solution is that you forgot to put the a return or even better put a Parenthesis around the object that is being return by the updater func.
in your case
this.setState(prevState => ({
todoItems: prevState.todoItems.map(item => {
if (item.id === todoItem.id) {
return {...todoItem};
}
return item;
}))
})
Thanks to ryanhinerman
for their answer on Reddit as outlined below.
The better solution is to not save the data from props inside the constructor. Instead, use this.props.todoItem directly. If you want to make it look prettier, you can destructure it at the top of the TodoItem's render function like so: const { todoItem } = this.props;
What's actually happening here is going to be slightly difficult to explain, but it's important to your understanding of React, so hopefully I can do an okay job of explaining it.
constructor(props) {
super(props);
this.todoItem = this.props.todoItem;
}
This constructor is only going to be called one time for the lifetime of a component, at the initial creation. What you're doing here is taking this.props.todoItem at the initial creation and saving it inside the component. This constructor will not be called again, so this.todoItems will never be updated no matter how many times this.props.todoItems changes.
<TodoItem todoItem={todoItem} key={todoItem.id} />
Here we give our component a key, and when this key changes, React knows to recreate our component. Because the id of todoItem never changes, React never recreates that component. If we were to use todoItem.title or something, the key would change and the entire component would be reset and the constructor would be called again, "solving" the problem. This, however, isn't the correct solution.
The better solution is to not save the data from props inside the constructor. Instead, use this.props.todoItem directly. If you want to make it look prettier, you can destructure it at the top of the TodoItem's render function like so: const { todoItem } = this.props;
I have some data loaded in the store after initial Axios call.
Then I render two components match (parent component) and player (child component).
This is the way to show the two components in a related way (this is a simplified example from my original code, in this example I could solve my problem in another way, but in my complex real code it is essential to do an operations in children component first):
match.js
class Match extends Component {
constructor(props) {
super(props);
}
render() {
return (
Object.values(this.props.matchs).map(( match_id ) => {
let match = this.props.matchs[match_id];
return (
<div key={match_id}>
<p>{match.tournament}</p>
<p>{match.color}</p> {/* this color depends of children condition*/ }
<div className="players">
{match.array_players.map ( ( player_id ) => {
let player = this.props.players[player_id];
return (
<Player key={odd_id} ownPlayer={player} />
)
})
</div>
</div>
)
});
)
}
}
const mapStateToProps = state => {
return {
matchs: state.matchs.matchs,
players: state.players.players
};
}
const mapDispatchToProps = dispatch => {
return {
// actions
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Matchs);
player.js
class Player extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<p>{this.props.ownPlayer.name}</p>
<p>{this.props.player_color}</p>
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
// I need to make some previous operations before render
let player_color;
if (ownProps.ownPlayer.name == "paul")
player_color = 'yellow';
else
player_color = 'blue';
// Then I Need to update parent component with children color condition
// if (player_color == 'yellow')
// match_color = 'yellow'
//
// Call some action here to update parent component???
// things like these do not work:
// let id_p = ownProps.player.id_player;
// state.players.players[id_p].color = 'blue'; This does not work
return {
player_color
};
};
const mapDispatchToProps = dispatch => {
return {
//
}
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Player);
Then I need to update a prop in a parent component after some conditions in children component.
I've read this article:
https://redux.js.org/docs/recipes/ComputingDerivedData.html
But I don't know how to send data to store and refresh parent component before render.
I thought about calling like an action in componentWillMount or componentWillUpdate to send data to store, but I don't know if it's correct way.
There is nothing wrong with calling an action inside the lifecycle, it is not recommended to do it inside the render method because it my trigger infinite actions, but in your situation if you indeed have to do this calculation inside the child component I believe you should dispatch this action inside componentWillReceiveProps or ComponentDidMount, in some situations you actually have to do it in both places.
go for it!
The docs are pretty clear:
You can either do one-time ops in constructor / ComponentWillMount / ComponentDidMount or repetitive ops in recurring life-cycle methods like ComponentWillReceiveProps.
If you need a way for the child component to update the store, than you have to dispatch an action that will go and do so, and put it in ComponentWillMount or ComponentWillReceiveProps depending on the need, sometimes you need to put it in both.
But, on a side note, like Bruno Braga said, it does seem like the wrong place to put logic in.
I would suggest to put this logic in the reducer, as Component really shouldn't handle store logic, just notify (dispatch) state changes.
Also, I don't think that you need to connect the Player component to the redux store, since it seems like each player has it's own independent instance.
What I would suggest is passing the Player Component a function from the Match Component, something like
<Player ... onGoalScored={()=> this.handleGoalScored()} />
and on the Match component do:
handleGoalScore() {
this.props.dispatch(updateGoalsAction())
}
and have the logic in the reducer, the let's say will figure out what the color of Match should be, and, on the next state update to Match, because of the binding to store.matchs.color will be rendered as Red
I am trying to setState() to a query result I have from graphQL, but I am having difficulty finding out how to do this because it will always be loading, or it's only used from props.
I first set the state
constructor (props) {
super(props);
this.state = { data: [] };
Then I have this query
const AllParams = gql`
query AllParamsQuery {
params {
id,
param,
input
}
}`
And when it comes back I can access it with this.props.AllParamsQuery.params
How and when should I this.setState({ data: this.props.AllParamsQuery.params }) without it returning {data: undefined}?
I haven't found a way to make it wait while it's undefined AKA loading: true then setState. I've tried componentDidMount() and componentWillReceiveProps() including a async function(){...await...} but was unsuccessful, I am likely doing it wrong. Any one know how to do this correctly or have an example?
EDIT + Answer: you should not setstate and just leave it in props. Check out this link: "Why setting props as state in react.js is blasphemy" http://johnnyji.me/react/2015/06/26/why-setting-props-as-state-in-react-is-blasphemy.html
There is more to the problem to update props, but some great examples can be found at this app creation tutorial: https://www.howtographql.com/react-apollo/8-subscriptions/
A simple solution is to separate your Apollo query components and React stateful components. Coming from Redux, it's not unusual to transform incoming props for local component state using mapStateToProps and componentWillReceiveProps.
However, this pattern gets messy with Apollo's <Query />.
So simply create a separate component which fetches data:
...
export class WidgetsContainer extends Component {
render (
<Query query={GET_WIDGETS}>
{({ loading, error, data }) => {
if (loading) return <Loader active inline="centered" />;
const { widgets } = data;
return (
<Widgets widgets={widgets} />
)
}}
</Query>
)
}
And now the Widgets components can now use setState as normal:
...
export class Widgets extends Component {
...
constructor(props) {
super()
const { widgets } = props;
this.state = {
filteredWidgets: widgets
};
}
filterWidget = e => {
// some filtering logic
this.setState({ filteredWidgets });
}
render() {
const { filteredWidgets } = this.state;
return (
<div>
<input type="text" onChange={this.filterWidgets} />
{filteredWidgets.count}
</div>
)
}
}
What is the reason behind setting it to state? Keep in mind, Apollo Client uses an internal redux store to manage queries. If you're trying to trigger a re render based on when something changes in the query, you should be using refetchQueries(). If you absolutely need to store it in local state, I would assume you could probably compare nextProps in componentWillReceiveProps to detect when loading (the value that comes back when you execute a query from apollo client) has changed, then update your state.
I had a similar issue (although it was happening for a totally different reason). My state kept getting set to undefined. I was able to solve it with a React middleware. It made it easy to avoid this issue. I ended up using superagent.
http://www.sohamkamani.com/blog/2016/06/05/redux-apis/
It's easiest to explain what I'm trying to accomplish with an example:
addContact = ev => {
ev.preventDefault();
this.props.setField('contacts', contacts => update(contacts, {$push: [{name: 'NEW_CONTACT'}]}));
this.props.setFocus(`contacts.${this.props.data.contacts.length-1}.name`);
};
In this example, this.props.setField dispatches an action which causes an extra field to be added to my form.
this.props.setFocus then attempts to focus this new field.
This won't work because the form hasn't re-rendered yet when setFocus is called.
Is there any way to get a callback for when my component has been re-rendered after a dispatch call?
If you need to see it, setField looks like this:
setField(name, value) {
if(_.isFunction(value)) {
let prevValue = _.get(data, name);
if(prevValue === undefined) {
let field = form.fields.get(name);
if(field) {
prevValue = field.props.defaultValue;
}
}
value = value(prevValue);
}
dispatch(actions.change(form.id, name, value));
},
I would put
this.props.setFocus(`contacts.${this.props.data.contacts.length-1}.name`);
in componentDidUpdate and I would call it on some condition. Like let's say, prevProps.data.contact.length < this.props.data.contacts.
UPDATE
You should keep this:
addContact = ev => {
ev.preventDefault();
this.props.setField('contacts', contacts => update(contacts, {$push: [{name: 'NEW_CONTACT'}]}));
};
In a parent component, and in that component you will render all the sub components:
render() {
return {
<div>
{contacts.map(c => <ContactComponent key='blah' contact={c}>)}
<a onClick={addContact}>Add Contact</a>
</div>
};
}
Then your contact component, will be as you like, the same goes for all the other elements you want to accommodate with this functionality.
At that point, you're asking:
Where is the focus thingy?
What you need for this abstraction-ish is higher order composition. I will give you an example, but please make time to read about HOCs.
This will be you HOC:
function withAutoFocusOnCreation(WrappedComponent) {
// ...and returns another component...
return class extends React.Component {
componentDidMount() {
// contacts string below can be changed to be handled dynamically according to the wrappedComponent's type
// just keep in mind you have access to all the props of the wrapped component
this.props.setFocus(`contacts.${this.props.data.contacts.length-1}.name`);
}
render() {
return <WrappedComponent {...this.props} />;
}
};
}
And then in each child component you can use it as a decorator or just call it with your HOC and that's all. I won't write more, but do make the time to read more about HOCs, here is the official documentation's page
official documentation's page. But you can check Dan Abramov's video on egghead as well. I hope my answer helps you, please accept it if it does :) Take care!