modify a setState from the data retrieved via a link [duplicate] - javascript

This question already has answers here:
setState doesn't update the state immediately [duplicate]
(15 answers)
React slow setState at console.log
(1 answer)
Closed 3 years ago.
Hello everybody
I'm a young beginner in programmtion. I'm trying to recover data from a Link to another component. Everything works except just put this recovered data in a state object with setState. I think I don't know evrything possible about setState but I'm quite lost.
I have this link which send the data "Command_ID" :
<Link to={`/produits/${Command_ID}`} className="item" params={{ Command_ID: {Command_ID}}}>
And as expected, I recover data like this and I recall it "order_id" :
state = {orderId: null};
componentDidMount() {
const order_id = this.props.match.params;
console.log(order_id);
this.setState({orderID: order_id});
console.log(this.state.orderID);
}
I can see in my console.log(order_id) the right number recover in the link part with the good "Command_ID". But when I try to put it with the setState and see in my console if it works, I just have a value of undefined for this.state.orderID
Thank you for your help :)

setState is async method , to execute something after the state is set you can pass function as second parameter for setState
this.setState({orderID: order_id}, () => console.log(this.state.orderId));

Related

Next Js getInitialProps within a component not passing props [duplicate]

This question already has answers here:
NextJS getStaticProps() never called
(5 answers)
Closed 11 months ago.
I have having a rather frustrating time with Next Js and am hoping that someone will be able to help.
We have a component and I am trying to use "getInitialProps" to pass props to a component during the server-side rending process, however, nothing seems to come through. I'm pretty sure I've tried every permeation I can think of and the props never go through. I know that the getInitialProps is being fired because I see the console.log coming through in the command line.
const HeaderMain = (props) => {
return(
<>
<h1>props.name</h1> <!-- This is blank -->
</>
);
};
HeaderMain.getInitialProps = async ({ req }) => {
console.log({ req: req }) // this works
// Do some other stuff here
return {
name: "Paul"
}
}
export default HeaderMain
If anyone could give me a point in the right direction it would be greatly appreciated.
In the end, we have decided to send the data from the main page through props to the component. It took quite a bit of digging around to see how the rendering engine works to get it to work the way we wanted it to work.

How does this useState hook work in React? [duplicate]

This question already has an answer here:
Why does useState cause the component to render twice on each update?
(1 answer)
Closed 2 years ago.
const App = () => {
const [ counter, setCounter ] = useState(0)
console.log(counter)
return (
<>
<div>You clicked {counter} times.</div>
<button onClick={ () => setCounter(counter+1) }>Click me!</button>
</>
)
}
Here's my react component. My question is when I run this, I see 0 two times in the console. Then when I click on the button, I see 1 two times in the console. Can anyone explain why does that happen? I was expecting 0, 1, 2 to be printed only once in the console whenever I click on the button.
Please forgive if this question has already been answered or my title of the question is not related with what I'm asking as this is my first question here.
It is because of React.StrictMode
If you go to your index.js , you will find that your App component is wrapped with <React.StrictMode>. If you strip off the StrictMode you will notice that your App component will render only once.
Refer the below doc to understand StrictMode
Strict mode can’t automatically detect side effects for you, but it
can help you spot them by making them a little more deterministic.
This is done by intentionally double-invoking the following functions:
Class component constructor, render, and shouldComponentUpdate methods
Class component static getDerivedStateFromProps method Function
component bodies State updater functions (the first argument to
setState) Functions passed to useState, useMemo, or useReducer
Please refer: https://reactjs.org/docs/strict-mode.html
return (<React.StrictMode><App /><React.StrictMode>)
This would solve your problem.

Problems setting useState inside onClick handler [duplicate]

This question already has answers here:
Why does calling react setState method not mutate the state immediately?
(9 answers)
How does JavaScript mechanism behind react hooks work?
(2 answers)
Closed 3 years ago.
I am using useState hook inside onClick handler to change and track the focus state. I set it to false initially and then change it to true and false several times in the handler. After each change, I do console.log(focus) and I expect it to be respective to the changes made.
function App() {
const [focus, setFocus] = useState(false);
return (
<div
className="App"
onClick={() => {
console.log(focus);
setFocus(true);
console.log(focus);
setFocus(false);
console.log(focus);
}}
>
<h1>App</h1>
</div>
);
}
In my case, in this code snippet, I expect to see in console false, true and then false again, but I see all of them false.
Why does it happen? I feel I am missing something quite fundamental here.
When you set the state, the component will be re-rendered. State changes are not synchronous in nature. Try adding a console.log below your useState line and you'll see that it gets called every time you set the focus because the entire component is re-rendered.

How to get the parameter in React using history.push [duplicate]

This question already has answers here:
How to pass params with history.push/Link/Redirect in react-router v4?
(13 answers)
Closed 3 years ago.
I am using history.push in React in a specific page inside a function so that once the button is clicked it pushes to a specific page
someFunction (paramToPass) {
this.props.history.push('/abcfolder/TheFileToReceiveParam',{paramToPass });}
I want to get paramToPass in TheFileToReceiveParam when the page is open but I dont know how to do this.
Would be a big help if anyone can help.
Once you have passed your parameter this way :
this.props.history.push('/my-path', { myParam: paramToPass });
You can retrieve this parameter using the 'location' property of your destination component:
this.props.location.state.myParam;
According to the React Router documentation, here's an example of what the location object looks like:
{
key: 'ac3df4', // not with HashHistory!
pathname: '/somewhere'
search: '?some=search-string',
hash: '#howdy',
state: {
[userDefined]: true
}
}

setState doesnt seem to update the state [duplicate]

This question already has answers here:
Why does calling react setState method not mutate the state immediately?
(9 answers)
Closed 5 years ago.
onSelectedRow(user, clickEvent){
const state = this.state;
this.state['userId'] = clickEvent.target.getAttribute(user['mta:UserId']);
this.setState(state);
console.log(user['mta:UserId']);
console.log(this.state);
}
Okay, so when I click a table-cell in my app this function gets called.
The point of it is to take the users UserId and set the state. This UserId is later on passed down to a child component and used to get specific information. The problem is that I get the correct data in the first console.log but when I then log this.
state the userId is still null for some reason. Anyone had similiar problems?
It's most probably because you're not updating the const state, but instead trying to mutate the state itself.
Also, you don't have to make a copy of a state. You can update just the field you want to update like this:
onSelectedRow(user, clickEvent) {
this.setState({
userId: clickEvent.target.getAttribute(user['mta:UserId'])
}, () => { console.log(this.state.userId) });
console.log(user['mta:UserId']);
}
Also, your console.log won't read immediate change in the state as setState is an async action.
If you really want to read it you can pass the callback to the setState which fill fire right after the state is updated, or use React's lifecycle method componentDidUpdate().

Categories