react-redux current props value - reactjs

I've three buttons on the page, and when clicking on any button i want to get that selected value from the store filtered by id(done in reducer). I'm trying to use redux with mapStateToProps and mapDispatchToProps pattern, but looks like when i try to access the current selected value from the store after clicking on any button, it doesn't reflect the correct value in the console. Is this not how "this.props.anyPropValue" be used? Can you help clarify what's wrong in my example?
First time it prints default value when clicking any button, clicking again prints the previously clicked button value not the current one.
Here is a sandbox link to the simple app i created for the above
sandbox link of the code

Most of the code that you have wrote is correct, If you are expecting to see the updated output right after calling the action, it won't work
onGetCountryById(id) {
this.props.fetchCountryById(id);
console.log(this.props.country); // This will gives you the current country (We just update the state, but still that value didn't update the component)
}
try to print the value of the country in the html as below and you will see it's getting updated
{this.props.country === null ? "default" : this.props.country.name}
in the reducer you might need to do this change
case CountryActions.FETCH_COUNTRY_BY_ID:
return {
...state,
country: state.countries.find((item) => item.id === action.id) // use find instead of filter
};
and set the initial value of the country set to null
const initCountriesState = {
country: null,
countries: [
....
]
};
here is the updated sandbox

Related

React nested state object not updating

I am trying to update a nested state object (checkedObjects) in a react class component, to track when checkboxes are checked and unchecked. checkedObjects has the following structure:
checkedObjects: {
[assignmentName]: boolean,
}
verifyObjects is a local variable that checks if the new name property was actually received. When I console out the contents of these objects however, checkedObjects is empty, while the new property was added to verifyObjects (see screenshot below). Can anyone advise why the state variable checkedObjects is not updating immediately?
Screenshot:
Code Snippet:
this.state = {
checkedObjects: {},
};
incrementCount(totalCount, id, checked, assignmentName) {
console.log("increment: totalCount", totalCount, " ; id:", id, checked);
// If a checkbox is clicked with an assignment name store on the checkedObjects
if (assignmentName) {
let verifyObjects = { ...this.state.checkedObjects };
verifyObjects[assignmentName] = checked;
this.setState(prevState => {
let tempObj = {...prevState.checkedObjects}
tempObj[assignmentName] = checked;
return {checkedObjects: tempObj}
});
console.log("SelectedAssignmentsObj:", this.state.checkedObjects);
console.log("VerifiedObject:", verifyObjects);
} //if
}
State updates don't occur instantaneously. When we call the setState() function, it schedules a state update. Try console logging tempObj to see the value that is being put inside of this.state.checkedObjects.
In short, your code is working the way it should but you wont be able to see the state update right after calling this.setState() [because the state update is scheduled and didnt happen at that instant]. If you want to ensure that your state did update the way you wanted, can add a dummy button on the side that console logs the value of this.state.checkedObjects or you can use the chrome extension React Developer Tools to find out the values in the state object.

Framer / React: Can't change focus state of Text Input onClick / onChangePage

This is a Framer/React question:
I have a bunch of text fields in a "page" component and I want the focus to shift on every "page" change.
There's a button controlling the pager but no trigger (onPageChange / onClick) is changing the attribute of "focus" on the relevant text input.
This is the code I tried using to change the value of foc2 (the focus attribute) to true
When I manually change it to true it works, but in this case it doesn't
export function Page(): Override {
return {
currentPage: state.page,
onChangePage: (index) => {
state.page = index
state.foc2 = true
},
}
}
Do you have more complete code you could share?
Make sure you set the state to the index of the current focused input, and use that to change the currentPage property.
Happy to help if you send more context, you can also find more help in Framer's community at https://framer.com/r/discord

ReactJS: Updated filled forms and return to initial state after cancel

I'm currently wondering how to go back to the form's initial state after cancel.
Here is the scenario:
I have a user information form that I need to update.
In the form, I can already see my data.
I changed a value in one of the fields.
After changing the value, I realized I do not want to update it yet so I click cancel.
When I click on Cancel, it should go back to the original data.
My current situation is that when I click on cancel, I am using resetFields(); function which clears all the input fields.
const cancel = () => {
form.resetFields()
}
Are there any suggestions?
You need to save the initial state, on cancel not .resetFields() but use .setFields({}) to reset.
Read docs about form instance
Here example:
form.setFields({ ...state })
Initial state save in this format:
{
firstInput: {
value: 'value', errors: []
},
secondInput: {
value: 'value', errors: []
}
}

Office UI Fabric React - Dropdown not respecting selectedKey prop

I have this code:
<Dropdown
selectedKey={someKeyInState}
onChange={(e,option) => {
// check if the dropdown should be updated
if(someCondition){
// update selected key
}
else {
// don't update selected key
}
}}
options={someOptions}
/>
I want to block updating the selected key if a certain condition is met.
But, Dropdown visually shows the option that I clicked on as selected.
How do I prevent this behavior?
If you are using react, you should not do in this way. Use a global state optionState and try to use conditional checks which state should be shown to use onChange method is triggered. In order to do this. First extract your conditional check to separate function.
myFunction = () => {
// do conditional check and setState for optionState
}
--------------------------
onChange={myFunction}
Then when you select pop the key and value from the option state and update to the selectedState, now react automatically update the state and UI
The problem was my state for selectedKey was undefined it nothing is selected. When you pass in undefined you're basically saying to fabric to control the selectedKey state on it's own. I fixed by passing null instead of undefined. That made the Dropdown fully controlled.

Check if the state value is date in reactjs

I am new to reactjs and want to know if there is a way to check if the state value is datetime in reactjs.
What i am trying to do?
On clicking the checkbox i set its state to current date and time. But its value is not updating meaning after clicking submit button it doesnt update the checkbox....the checkbox isnot checked even though user checks it. How do i check if the value of the variable is datetime. Below is the code...Could someone help me with this. Thanks.
class Name extends React.PureComponent {
constructor(props) {
super(props);
const topic = props.topic;
this.state = {
checkbox_checked: some_value ? some_value.property : null,
};
}
handle_checkbox_change = (event) => {
this.setState({'checbox_checked': (event.target.checked === true ? timeUtils.date_to_iso_format(new Date()) : null)}, () => console.log('checkbox status:', this.state.checkbox_checked));
};
render () {
return (
<input
name="checkbox_name"
checked={state.resolved}
onChange={this.handle_checkbox_change}
type="checkbox"/>
<span>Checkbox</span>
<button type="submit">
</button>);}}
There is so many functions that helps you check if the value is a date that you can find them by a simple search. take a look here for example of some of these functions:
Check if a string is a date value
Also, you can make some changes to the code:
this.state = {
// Checkbox is either false or true so edit this according to your some_value
checkbox_checked: some_value ? true: false,
// And the date if it's checked. it can be null at initial state.
// You can set a date if you have a date.
checkbox_checked_date: null
};
And whenever your checkbox changed or user clicked on it, it means that the state should change.
So:
handle_checkbox_change = (event) => {
// checbox_checked will change whenever user clicked on checkbox
this.setState({checbox_checked: !this.state.checbox_checked, checkbox_checked_date: timeUtils.date_to_iso_format(new Date())})
};
Now everytime user clicked on checkbox your code will change the state of the checbox_checked. Then when your submiting and sending your data to some API or anywhere you might need them, just check if checbox_checked is true and if it was, then check for checkbox_checked_date, if it was null, it means that checkbox was already set to true (Your initial state - if you can't set any date for initial state otherwise you should check if the date is too behind meaning it was already checked) and if checkbox_checked_date wasn't null, it means that user changed the checkbox to true in the date you have as checkbox_checked_date and you can be sure that is for sure a date and treat it accordingly.
This way your code is way cleaner and has more features available easily for future development.

Resources