State is not getting initialized to the initial state of reducer - javascript

I am new to the react redux . Here, what I am doing is ,
const initialState = {
Low: [
{
id: 0,
technologyId: 0,
technology: '',
level: 'EASY'
}
],
Medium: [
{
id: 0,
technologyId: 0,
technology: '',
level: 'MEDIUM'
}
],
High: [
{
id: 0,
technologyId: 0,
technology: '',
level: 'TOUGH'
}
]
}
Now,In my reducer ,
export default function QuizData(state = initialState, action) {
switch (action.type) {
case QUIZ_DATA:
return {
...state,
Low: action.data,
error: false,
}
case RESET_QUIZ_CRITERIA: {
console.log("intial state is ", ...state);
return {
...state
}
Now, here what happens is after some manipulations, this objects gets changes with every key is having some values. like,
So, This gets changed.
{
Low: [
{
id: 0,
technologyId: 11,
technology: 'xsxs',
level: 'EASY'
}
],
Medium: [
{
id: 0,
technologyId: 22,
technology: 'swwsw',
level: 'MEDIUM'
}
],
High: [
{
id: 0,
technologyId: 110,
technology: 'xsxsx',
level: 'TOUGH'
}
]
}
for resetting my action is like ,
export function resetPreviousQuizSelectionCriteria() {
console.log("Calling this");
return {
type: RESET_QUIZ_CRITERIA
}
}
Now, what I want to do is that ,
When user clicks a button that time I want to change this to the initial state.
So that it will not have any values as it should be same as by default.
So, Can any one one suggest me the solution?

I think returning initial State should resolve the issue.
case RESET_QUIZ_CRITERIA: {
console.log("intial state is ", ...state);
return {
...initialState
}
try this if it works.

Related

how to simplify the length of the state in react js

import { OrderSummary } from "#/services/order/data";
Below is my state declaration
let [orderSummary, setOrderSummary] = useState<OrderSummaryResponse>({
Id: 0,
TableId: 0,
TableName: '',
MerchantId: 0,
StoreId: 0,
StoreName: '',
BrandName: '',
IsUnifyQR: false,
Discount: 0,
ServiceCharge: 0,
GST: 0,
RoundingAdjustment: 0,
TotalAmount: 0,
SubTotalAmount: 0,
ServiceChargeAmount: 0,
GSTAmount: 0,
CreatedAt: '',
Items: [
{
MerchantId: 0,
StoreId: 0,
StoreName: '',
ItemId: 0,
ProductId: 0,
ProductName: '',
TotalAmount: 0,
Quantity: 0,
Note: '',
Choices: [
{
OptionSelectedName: '',
ProductOptionId: 0,
OptionSelected: null,
MultiOptionsSelected: null,
OneChoiceWithValueSelected: {
OptionSelected: 0,
Quantity: 0,
Price: 0,
},
MultioptionWithValueSelected: [],
},
],
},
],
Categories: [''],
});
if I have a few usestate like above, my code looks very lengthy how to simplify that.
getting error if I use like this
let [orderSummary, setOrderSummary] = useState<OrderSummary>({})
let [orderSummary, setOrderSummary] = useState<OrderSummary>({} as any)
You can use type like this:
let [orderSummary, setOrderSummary] = useState<OrderSummary | null>(null)
And when you want to use orderSummary. You can add optional chaining like this:
orderSummary?.StoreId

Multidimensional state update in reactjs

I am working with a complex state object in reactjs and I am unable to update a particular item of the state.
state = {
order: {
jobs: [
{
id: "1",
jobId: "31147-02",
services: [
{
id: 18,
price: "100",
},
{
id: 19,
price: "100",
},
{
id: 65,
price: "3200",
},
{
id: 87,
price: "1800",
},
{
id: 88,
price: "1350",
},
{
id: 89,
price: "1350",
},
],
},
{
id: "2",
jobId: "31147-02",
services: [
{
id: 45,
price: ""
},
{
id: 41,
price: "",
},
{
id: 28,
price: "",
},
],
},
],
},
};
And trying to handle delete functionality
Following code of is receiving the index of JOB and the object of service which needs to be removed from the state to perform delete functionality.
handleJobServiceDelete = (jobId, service) => {
let jobs = [...this.state.order.jobs[jobId].services];
jobs = jobs.filter((s) => s.id !== service.id);
console.log(jobs);
this.setState({ jobs });
};
But I am unable to setState with updated service array after removing object from it.
You'd need to use this.setState({ order: { jobs } });, but that wouldn't work because React won't set the state fully, so it takes a bit more.
this.setState((prevState)=>({ order: {...prevState.order, jobs } }));
The way I would ordinarily manage deeply nested state like this is using https://github.com/kolodny/immutability-helper as it makes it much easier to manage.
Edit: Fixed the full issue using immutability helper. There were different issues than I originally noticed. I didn't realize due to the variable names that the data being altered was the job's services and so had to go back into the job's services rather than replacing the jobs.
import update from 'immutability-helper';
this.setState((prevState) => {
const idx = prevState.order.jobs[jobId].services.findIndex(
(s) => service.id === s.id
);
return {
order: update(prevState.order, {
jobs: { [jobId]: { services: { $splice: [[idx, 1]] } } },
}),
};
});

how to change or update the specific value of the state immutably

I'm new to js and react js with redux i'm trying to update a value of the global state immutably This is my current state
const initialState = {
questions: [
{
id: 1010,
name: "Inside which HTML element do we put the JavaScript?",
questionTypeId: 1,
options: [
{
id: 10,
name: "javascript",
isAnswer: false,
isSelected: false
},
{
id: 11,
name: "scripting",
isAnswer: false,
isSelected: false
},
{
id: 12,
name: "script",
isAnswer: true,
isSelected: false
},
{
id: 13,
name: "js",
isAnswer: false,
isSelected: false
}
]
},
{
id: 1011,
name: "Javascript is a langague used for ?",
questionTypeId: 2,
options: [
{
id: 14,
name: "ConsoleApp",
isAnswer: false,
isSelected: false
},
{
id: 15,
name: "ShellApp",
isAnswer: false,
isSelected: false
},
{
id: 16,
name: "WebApp",
isAnswer: true,
isSelected: false
},
{
id: 17,
name: "MobileApp",
isAnswer: false,
isSelected: false
}
]
},
{
id: 1012,
name: "What is the full form of SPA?",
questionTypeId: 3,
options: [
{
id: 18,
name: "Secured and Progressive App",
isAnswer: false,
isSelected: false
},
{
id: 19,
name: "Single Page Application",
isAnswer: false,
isSelected: false
},
{
id: 20,
name: "SOLID Principles for Application",
isAnswer: true,
isSelected: false
},
{
id: 21,
name: "None of the above",
isAnswer: false,
isSelected: false
}
]
}
],
Currentquestion: []
};
i would like to change the isSelected value to true from the questions array of which index having questionTypeId:1 followed by the options array of index:0
Below is the reducer i tried to change the state immutably action.payload value from the ui is 1 and action.value's value from the ui is 0
case SELECT_ANS: {
const question = action.payload;
const index = action.value;
// const newstate = produce(state, draftsate => {
// draftsate.questions[question].options[index].isSelected = true;
// });
return {
...state,questions:[
{
...state.questions[question],options:[{
...state.questions[question].options[index],isSelected:true
}]
}
]
]
]
};
I try to put all the information as much as i can if anything missing or inappropriate i'm sorry about ,Any help with explanation would be really appriciated ,Thanks in Advance
At first I notices you split your action's data into action.payload and action.value, this is against the flux principles. You must put your data object in action.payload and get it like action.payload.questionTypeId and action.payload.index.
Well, you can change your store like
case SELECT_ANS: {
return {
...store,
questions: store.questions.map((question) => {
if (question.questionTypeId === action.payload.questionTypeId) {
return {
...question,
options: question.options.map((option, index) => {
if (index === action.payload.index) {
return {
...option,
isSelected: true,
};
}
return option;
}),
};
}
return question;
}),
};
};
If I didn’t answer your question well enough, you can get more information in redux docs or ask me personally.
Good luck learning!

Update the redux state in the reducer having array of objects

I am new to the react-redux.
I do have an object which is like,
const initialState = {
Low: [
{
id: 0,
technologyId: 0,
technology: '',
level: 'EASY'
}
],
Medium: [
{
id: 0,
technologyId: 0,
technology: '',
level: 'MEDIUM'
}
],
High: [
{
id: 0,
technologyId: 0,
technology: '',
level: 'TOUGH'
}
]
}
Now,
export default function QuizData(state = initialState, action) {
switch (action.type) {
case QUIZ_DATA:
return {
...state,
Low: action.data,
error: false,
}
case RESET_SETUP_QUIZ: {
console.log("intial state is ", ...state);
return {
...state
}
Now, here what happens is after some manipulations, this objects gets changes with every key is having some values. like,
{
Low: [
{
id: 0,
technologyId: 11,
technology: 'xsxs',
level: 'EASY'
}
],
Medium: [
{
id: 0,
technologyId: 22,
technology: 'swwsw',
level: 'MEDIUM'
}
],
High: [
{
id: 0,
technologyId: 110,
technology: 'xsxsx',
level: 'TOUGH'
}
]
}
So, This gets changed.Now, what I want to do is that ,
When user clicks a button that time I want to change this to the initial state.
So that it will not have any values as it should be same as by default.
SO, what I tried it
return {
initalState
}
But here, initial state is also having the same values.
So, I am not getting a way to make it to the initial level.
Can one help me with this ?
Because you use the original state object and return a modified version of it (i.e. you do affect your initialState).
You must create a copy of the state in your reducer, for example
case QUIZ_DATA:
return Object.assign(
{},
state,
{
Low: action.data,
error: false
}
)
case RESET_SETUP_QUIZ: {
return Object.assign(
{},
state
)
}
You have dedicated librairies like immutablejs to handle this
(https://redux.js.org/recipes/usingimmutablejs)

Update the property of a array of object in react js

I am new to the react-redux.
Here I have an object which is like,
const initialState = {
Low: [
{
id: 0,
technologyId: 0,
technology: '',
type: '',
count: '',
allowded: 6,
level: 'EASY'
}
],
Medium: [
{
id: 0,
technologyId: 0,
technology: '',
type: '',
count: '',
allowded: 7,
level: 'MEDIUM'
}
],
High: [
{
id: 0,
technologyId: 0,
technology: '',
type: '',
count: '',
allowded: 7,
level: 'TOUGH'
}
]
}
Now, this value is set it in the reducer I am taking it as a props.
Now, onchnage here the object property gets change from one of these obj.
So, Here the way I am updating it is ,
onChange(event, tobeupdated, id, type, noc, data) {
let newData = { ...this.props.data };
if (newData) {
let data = newData[type].map((object, index) => {
if (object.id === id) {
object[tobeupdated] = event.target.value;
});
}
}
So,Here will I be updating the existing object ?
Or is there any another way ?
What I tried was,
{...object, [tobeupdated]: event.target.value}
it is giving the compile time errors .
How can I resolve this ?

Categories