I have a react app I have a function that is updating an object with setState. I pass the data to another component with props and I make a console.log.
console.log(workingHours, workingHours.monday.startHourMonday);
in the first dump the object working hours have the values
{
"monday": {
"startHourMonday": "9:0",
"endHourMonday": "19:0"
},
"tuesday": {
"startHourTuesday": "9:0",
"endHourTuesday": "19:0"
},
"wednesday": {
"startHourWednesday": "9:0",
"endHourWednesday": "19:0"
},
"thursday": {
"startHourThursday": "9:0",
"endHourThursday": "19:0"
},
"friday": {
"startHourFriday": "9:0",
"endHourFriday": "19:0"
}
}
but the problem is for the key monday
{
"startHourMonday": "",
"endHourMonday": ""
}
the dumped values are empty.
the function that is updating the data
const [response, setResponse] = useState([]);
const workingHoursData = (response) => {
return response.map( el => {
workingHours.monday = {startHourMonday:el.startHourMonday, endHourMonday:el.endHourMonday};
workingHours.tuesday = {startHourTuesday:el.startHourTuesday, endHourTuesday:el.endHourTuesday};
workingHours.wednesday = {startHourWednesday:el.startHourWednesday, endHourWednesday:el.endHourWednesday};
workingHours.thursday = {startHourThursday: el.startHourThursday, endHourThursday:el.endHourThursday};
workingHours.friday = {startHourFriday:el.startHourFriday,endHourFriday: el.endHourFriday}
})
}
useEffect(() => {
try {
apiOperations.getData("configs").then(response => {
setResponse(response.data)
}).catch(e => {
props.history.push(adminLogin);
})
} catch (e) {
console.log(e)
}
}, [])
useEffect (() => {
workingHoursData(response);
},[response])
somebody know why?
Update:
the problem is I set direct the states values in the object. I must use setState function.
You can create separate state for working hours and record the response right there. Also I wrote shorthand for formatting your resposne to what you need.
const [response, setResponse] = useState([]);
const [workingHours, setWorkingHours] = useState({})
const weekdays = ['monday', 'tuesday', 'wendesday', 'thursday', 'friday']
const upperFirstLetter = (word) => word[0].toUpperCase() + word.slice(1)
useEffect(() => {
try {
apiOperations.getData("configs").then(response => {
setResponse(response.data)
}).catch(e => {
props.history.push(adminLogin);
})
} catch (e) {
console.log(e)
}
}, [])
useEffect (() => {
const formatResponse = weekdays.reduce((obj, day) => ({
...obj,
[day]: {
startHour: response[`startHour${upperFirstLetter(day)}`],
endHour: response[`endHour${upperFirstLetter(day)}`]
}
}), {})
setWorkingHours(formatResponse);
},[response])
I think, there is no reason to name startHourMonday because monday.StartHourMonday is a little bit wordy, but if you need to create exatcly this field, simply replace
startHour: response[`startHour${upperFirstLetter(day)}`]
with
[`startHour$(upperFirstLetter(day)}`]: response[`startHour${upperFirstLetter(day)}`]