Currently, I'm making a system that can control home electrical equipment on the web.
Backend is ready,
I'm trying to implement a function to adjust the brightness of the light with a slider.
I can set brightness_value variable is assigned a number from 0 to 100 when the slider is moved with the code below.
<input type="range" name="speed" min="0" max="100"
value={brightness_value} onChange={(e) => setBrightnessValue(e.target.value)}></input>
The problem is that I want to fire the lightOn function at the same time as I move the slider but I don't know what to do.
(I'm already using onChange, so can't I use it?)
LightDetail.js
import React, { useState, useEffect, useCallback, onClick} from 'react';
import axios from 'axios';
import ic_light from "../../images/icons/ic_light.png"
const LightDetail = () => {
const [light, setLight] = useState([]);
const [brightness_value, setBrightnessValue] = useState();
// set light strength
const lightOn = async(data) => {
await axios.post('xxx.com/light/turn_on',
{
brightness: brightness_value
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
console.log('Turn on!');
getDevices();
})
.catch(err => {
console.log('Turn on Missed!');
});
}
// get light data from backend
const getDevices = async(data) => {
await axios.get('xxx.com/device_listr',
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
console.log(result.data)
setLight(result.data.attributes.light);
})
.catch(err => {
console.log(err);
});
}
useEffect(() => {
getDevices();
}, []);
return (
<div className="container">
<div className="row mx-auto text-center">
<>
{light.map((item,i) =>
<div key={i} className="col-12">
<div className="box h-100">
<img className="" src={ic_light} />
<input type="range" name="speed" min="0" max="100"
value={brightness_value} onChange={(e) => setBrightnessValue(e.target.value)}></input><br></br>
<Link to={`/device_list`} className='btn btn-primary col-4'>Back</Link>
</div>
</div>
)}
</>
</div>
</div>
);
}
export default LightDetail;
You can define onChange as a custom event handler where you can do whatever.
Example snippet:
const handleSliderChange = (e) => {
setLightOn(e.target.value)
setBrightnessValue(e.target.value)
}
...
<input type="range" name="speed" min="0" max="100"
value={brightness_value} onChange={handleSliderChange} />
You should use the state to drive the view of the view to do
Just add
useEffect(() => {
lightOn()
}, [brightness_value])
Related
I get output from an api and store it in a state setInfoMetrics(data.info);
And I put this value in the input value | the value is displayed correctly but I cannot change the value
this is my sate : const [infoMetrics, setInfoMetrics] = useState([]);
useEffect(() => {
const fetchMetricsInfo = async () => {
try {
const { data } = await axios.get(
`API ADDRESS`,
{ headers: { Authorization: `Bearer ${token}` } }
);
setInfoMetrics(data.info);
} catch (error) {
console.error(error.message);
}
};
fetchMetricsInfo();
}, []);
THIS IS MY INPUT AND I CAN'T CHANGE THIS VALUE:
<div className="form-row">
<div className="col-md-12 mb-3">
<div className="titrExplain">Title</div>
<input
value={infoMetrics.summary_interpretation}
type="text"
className="form-control"
name="summary"
placeholder="Summary"
required
onChange={(e) => setSummary(e.target.value)}
/>
</div>
//this is my sate :
const [infoMetrics, setInfoMetrics] = useState([]);
useEffect(() => {
const fetchMetricsInfo = async () => {
try {
const { data } = await axios.get(
`API ADDRESS`,
{ headers: { Authorization: `Bearer ${token}` } }
);
setInfoMetrics(data.info);
//case 1
//your summary functions
setSummary(/*what you want*/)
} catch (error) {
console.error(error.message);
}
};
fetchMetricsInfo();
}, []);
//Case2
//listening on infoMetrics changes and do something
useEffect(()=>{
//your summary functions
setSummary(/*what you want*/)
},[infoMetrics])
//THIS IS MY INPUT AND I CAN'T CHANGE THIS VALUE:
<div className="form-row">
<div className="col-md-12 mb-3">
<div className="titrExplain">Title</div>
<input
value={summary}
type="text"
className="form-control"
name="summary"
placeholder="Summary"
required
onChange={(e) => setSummary(e.target.value)}
/>
</div>
Value and onChange, attributes of should be the same set [value,setValue] of useState. Case1 and Case2 choose one and it might work.
I need to be able to parse obj to another component called GuestForm.
However when i try to set obj.first_name i can see in the console that the the obj.first_name value is empty.
On top of having the object empty i would like to parse it to the component.
import React, { Component, useState, useEffect } from 'react';
import GuestForm from '../../components/Guests/GuestForm.js';
import { useParams } from 'react-router-dom';
import axios from "axios";
function Edit() {
const { id } = useParams();
const [mode, setMode] = useState('edit');
const [successMessage, setsuccessMessage] = useState('The guest has been edited successfully!');
const [action, setAction] = useState('/guests/edit');
const obj = {first_name: '', last_name: '', email: '', password: ''};
const headers = {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
"Accept": "application/json"
}
const res = fetch(process.env.REACT_APP_API_URL + action, {
method: 'POST',
headers: headers,
body: JSON.stringify({data: {id: id}}),
})
.then((response) => response.json())
.then((responseJson) => {
//return responseJson.json.guest;
obj.first_name = responseJson.json.guest.first_name;
})
.catch((error) => {
console.error(error);
});
console.log(obj); // Empty value for first name here...
return (
<>
<div className="container">
<GuestForm mode={mode} successMessage={successMessage} obj={obj} action={action} />
</div>
</>
);
}
export default Edit;
GuestForm
Here the component GuestForm which should display first name value in the field
import React, { Component, useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link, useHistory } from 'react-router-dom';
// react-bootstrap components
import {
Button,
Card,
Form,
Row,
Col,
} from "react-bootstrap";
import axios from "axios";
import { toast } from 'react-toastify';
function GuestForm({mode, successMessage, obj, action}) {
const history = useHistory();
const [details, setDetails] = useState([]);
const [loading, setLoading] = useState(false);
const [first_name, setFirstName] = useState(obj.first_name);
const [last_name, setLastName] = useState(obj.last_name);
const [email, setEmail] = useState(obj.email);
const [password, setPassword] = useState(obj.password);
const handleSave = e => {
e.preventDefault();
setLoading(true);
axios({
method: "POST",
url: process.env.REACT_APP_API_URL + action,
headers: { 'Content-Type': 'application/json;charset=UTF-8', "Access-Control-Allow-Origin": "*", "Accept": "application/json" },
data: {
data: obj
}
}).then(result => {
if(result.data.json.error == false) {
toast(successMessage, {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
history.push('/dashboard/guests');
}
setDetails(result.data.json);
setLoading(false);
});
};
return (
<>
<div className="container">
<div class="row">
<div class="col-lg-12">
<h1 className="mt-0 mb-4 green-color">{mode == 'edit'? <span>Edit</span>: 'New' } Guest</h1>
</div>
</div>
<Form onSubmit={handleSave} autoComplete="off">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 mt-2">
<Form.Group>
<label htmlFor="exampleInputEmail1">
Email Address
</label>
<Form.Control
value={email}
onChange={e => setEmail(e.target.value)}
type="email"
autoComplete="off"
></Form.Control>
</Form.Group>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 mt-2">
<Form.Group>
<label>Password</label>
<Form.Control
value={password}
onChange={e => setPassword(e.target.value)}
type="password"
autoComplete="new-password"
></Form.Control>
</Form.Group>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 mt-2">
<Form.Group>
<label>First Name</label>
<Form.Control
value={first_name}
onChange={e => setFirstName(e.target.value)}
type="text"
autoComplete="off"
></Form.Control>
</Form.Group>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 mt-2">
<Form.Group>
<label>Last Name</label>
<Form.Control
value={last_name}
onChange={e => setLastName(e.target.value)}
type="text"
autoComplete="off"
></Form.Control>
</Form.Group>
</div>
</div>
{(details.guest && details.error ) && <div className="error-message mt-4 mb-1">{details.message}</div>}
<Button
className="btn-fill pull-right mt-3"
type="submit"
variant="info"
disabled={loading}
>
{loading && <span>{mode == 'edit'? <span>SAVE CHANGES</span>: 'ADD' }...</span>}
{!loading && <span>{mode == 'edit'? <span>SAVE CHANGES</span>: 'ADD' }</span>}
</Button>
<div className="clearfix"></div>
</Form>
</div>
</>
);
}
export default GuestForm;
The reason your console.log is showing up as empty is because you are setting the value of obj.first_name in an asynchronous callback, but the actual logging line will be executed synchronously before that asynchronous callback is called. If you were to instead add another .then to the chain and do the console.log in there, you would see the updated value. Here's a snippet that demonstrates what I mean:
const obj = { a: 'b' };
Promise.resolve()
.then(() => {
obj.a = 'c';
})
.then(() => {
console.log('async:', obj);
});
console.log('sync:', obj);
If you want to send this value to GuestForm, you'll have to use a state variable that will be updated once the fetch call finishes. You also want to wrap this fetch call in a useEffect, so that calling setObj doesn't result in an endless loop (the fetch call causes the state update, which then causes the component to be re-rendered, which causes the fetch call to rerun, and so on). Something like:
import React, { Component, useState, useEffect } from 'react';
import GuestForm from '../../components/Guests/GuestForm.js';
import { useParams } from 'react-router-dom';
import axios from "axios";
function Edit() {
const { id } = useParams();
const [mode, setMode] = useState('edit');
const [successMessage, setsuccessMessage] = useState('The guest has been edited successfully!');
const [action, setAction] = useState('/guests/edit');
const [obj, setObj] = useState({first_name: '', last_name: '', email: '', password: ''});
const headers = {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
"Accept": "application/json"
}
useEffect(() => {
const res = fetch(process.env.REACT_APP_API_URL + action, {
method: 'POST',
headers: headers,
body: JSON.stringify({data: {id: id}}),
})
.then((response) => response.json())
.then((responseJson) => {
//return responseJson.json.guest;
const newObj = { ...obj, first_name:
responseJson.json.guest.first_name };
setObj(newObj);
})
.catch((error) => {
console.error(error);
});
}, []);
console.log(obj); // This will now show the updated value (but will still have the default value on the initial render)
return (
<>
<div className="container">
<GuestForm mode={mode} successMessage={successMessage} obj={obj} action={action} />
</div>
</>
);
}
export default Edit;
To use the updated value in GuestForm, you need to make sure your state variable is updated when the passed in prop is updated. This is best achieved with a useEffect. Add this to your GuestForm component
useEffect(() => {
setFirstName(obj.first_name);
}, [obj]);
This is necessary because you're duplicating the prop value with state variables in the child component. A more common pattern would be to pass both obj and setObj as props to GuestForm so that in the child you can modify the parent's state variable directly without creating a copy
I have a form that collect data about today's expenditure and total users(as attendances) and then submit it using redux dispatch via action addExpenses(). But it douse not run. It seem that it is not counting if it is present or not.
function TodayExpenses() {
const dispatch = useDispatch()
const navigate = useNavigate()
useEffect(() => {
dispatch(getAttendance());
}, [date, getAttendanceObj, dispatch, addExpenses])
const [todayExpenses, setTodayExpenses] = useState(0)
const { attendance: getAttendanceObj, error: getAttendanceError, loading: getAttendanceLoading } = useSelector(state => state.getAttendance)
const { success } = useSelector(state => state.addExpenses)
const submitHandler = (e) => {
e.preventDefault();
let expenses = {
date: date,
total_attendances: count,
expenses_per_day: todayExpenses,
expenses_per_attendance: expensePerAttendance,
}
dispatch(addExpenses(expenses)) // Here be the dragons
console.log(todayExpenses)
}
const today = new Date().toISOString().substr(0, 10);
const [date, setDate] = useState(today)
const count = counter(getAttendanceObj, date)
const expensePerAttendance = (todayExpenses / count).toFixed(2);
return (
<div className="container">
<div class="h1 text-center text-dark" id="pageHeaderTitle">
Enter <input type="date" id="date" value={date} onChange={(e) => setDate(e.target.value)} max={today} />'s Expenses
</div>
<div className="row">
<div className="col-md-6 mx-auto">
<div className="card card-body">
<form onSubmit={submitHandler}>
<label htmlFor="name">Today's Expenses:</label>
<input
type="number"
className="form-group"
id="name"
placeholder="Enter value"
value={todayExpenses}
onChange={(e) => setTodayExpenses(e.target.value)}
/>
<ul class="list-group list-group-flush">
<label class="list-group-item card-header">Total Attendances</label>
<li class="list-group-item">{count}</li>
<label class="list-group-item card-header">Expense Per Attendance</label>
<li class="list-group-item">{expensePerAttendance}</li>
</ul>
<button type="submit" className="btn btn-primary">
Submit
</button>
</form>
</div>
</div>
</div>
</div>
);
}
export default TodayExpenses;
What I have tried so far
What not? I tried console.log()even inside action but it working just above the required script ( I mean where the action have submit the data) .
if wanna ask here is action
export const addExpenses = (expenses) => async (getState, dispatch) => {
try {
dispatch({
type: ADD_EXPENSES_REQUEST
})
console.log("data:", dispatch({
type: ADD_EXPENSES_SUCCESS
}))
const { userLogin: { userInfo } } = getState();
const config = {
headers: {
'Content-type': 'application/json',
// 'Authorization': `JWT ${userInfo.token}`
}
}
const { data } = await axios.post(
'/api/expenses/post/',
expenses,
config
)
dispatch({
type: ADD_EXPENSES_SUCCESS,
payload: data
})
} catch (error) {
dispatch({
type: ADD_EXPENSES_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.response,
})
}
}
The dilemma is that I have copied it from other actions where it worked . I have also tried posting date using data manually using ThunderClient extention.(it is like insomnia or postman ) which mean there is no problem on the backend side.
Your thunk arguments are backwards. It should be (dispatch, getState)
export const addExpenses = (expenses) => async (dispatch, getState) => {
Hii i am getting an error when i am trying to filling a value in the form then getting error like "form data is not a function" dont know whats going on wrong please help as soon as possible
error img https://ibb.co/xMy002L
addmovie.js
here is my addmovie form where i wrote my whole logic
import React,{useState} from 'react';
import Navbar from '../pages/Navbar';
import Footer from '../pages/Footer';
import {Link} from 'react-router-dom';
import {isAuthenticated} from '../Auth/index';
import {addMovie} from '../Admin/adminapicall';
const AddMovie = () => {
const {user,token} = isAuthenticated();
const [values,setValues] = useState({
movie_name:'',
actor:'',
country_of_origin:'',
duration:'',
director:'',
photo:'',
loading:false,
error:'',
addedMovie:'',
getRedirect:false,
formData:''
})
const {movie_name,actor,country_of_origin,duration,director,photo,loading,error,addedMovie,getRedirect,formData} = values;
const handleChange = name => event => {
const value = name === "photo" ? event.target.files[0] : event.target.value
formData.set(name,value);
setValues({...values,[name]:value})
};
const onSubmit = (e) => {
e.preventDefault();
setValues({...values,error:'',loading:true})
addMovie(user._id,token,formData).then(data =>{
if(data.error){
setValues({...values,error:data.error})
}else{
setValues({
...values,
movie_name:'',
actor:'',
country_of_origin:'',
duration:'',
director:'',
photo:'',
loading:false,
addedMovie: data.movie_name
})
}
})
}
const successMessage = () => (
<div className='alert alert-success mt-3'
style={{display : addedMovie ? '' : 'none'}}>
<h4>{addedMovie} added successfully</h4>
</div>
)
// const successMessage = () => {
// }
const addMovieForm = () => (
<form >
<span>Post photo</span>
<div className="form-group">
<label className="btn btn-block btn-success">
<input
onChange={handleChange("photo")}
type="file"
name="photo"
accept="image"
placeholder="choose a file"
/>
</label>
</div>
<div className="form-group">
<input
onChange={handleChange("movie_name")}
name="photo"
className="form-control"
placeholder="movie_name"
value={movie_name}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("actor")}
name="photo"
className="form-control"
placeholder="actor"
value={actor}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("duration")}
type="number"
className="form-control"
placeholder="duration"
value={duration}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("country_of_origin")}
type="text"
className="form-control"
placeholder="country_of_origin"
value={country_of_origin}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("director")}
type="text"
className="form-control"
placeholder="director"
value={director}
/>
</div>
<button type="submit" onClick={onSubmit} className="btn btn-success mb-2">
Add Movie
</button>
</form>
);
return (
<div>
<Navbar/>
<div className='container'style={{height:'0px'}}>
<Link to='/admin/dashboard'> <h1 className=' bg-info text-white p-4 text-decoration-none'>Admin Home</h1> </Link>
<div className='row bg-dark text-white rounded'>
<div className='col-md-8 offset-md-2'>
{successMessage()}
{addMovieForm()}
</div>
</div>
</div>
<Footer/>
</div>
)
}
export default AddMovie;
adminapicall.js
this is code where my frontend talk with backend
import {API} from '../backend';
//products calls
//add movie
export const addMovie = (userId,token,movie)=>{
return fetch(`${API}/movie/addMovie/${userId}`,{
method : "POST",
headers:{
Accept:'Application/json',
Authorization: `Bearer ${token}`
},
body:movie
}).then(response => {
return response.json()
})
.catch(err => console.log(err))
}
//get all movie
export const getAllMovies = () => {
return fetch(`${API}/movies`,{
method : "GET"
})
.then(response => {
return response.json();
})
.catch(err => console.log(err))
}
//get a movie
export const getMovie = movieId =>{
return fetch(`${API}/movie/${movieId}`,{
method : "GET"
})
.then(response => {
return response.json();
})
.catch(err => console.log(err))
}
//update movie
export const updateMovie = (movieId,userId,token,movie)=>{
return fetch(`${API}/movie/${movieId}/${userId}`,{
method : "PUT",
headers:{
Accept:'Application/json',
Authorization: `Bearer ${token}`
},
body:movie
}).then(response => {
return response.json()
})
.catch(err => console.log(err))
}
//delete movie
export const deleteMovie = (movieId,userId,token)=>{
return fetch(`${API}/movie/${movieId}/${userId}`,{
method : "DELETE",
headers:{
Accept:'Application/json',
Authorization: `Bearer ${token}`
}
}).then(response => {
return response.json()
})
.catch(err => console.log(err))
}
i think ur mistaken here,
const [values,setValues] = useState({
movie_name:'',
actor:'',
country_of_origin:'',
duration:'',
director:'',
photo:'',
loading:false,
error:'',
addedMovie:'',
getRedirect:false,
formData:'' // <-
})
const {movie_name,actor,country_of_origin,duration,director,photo,loading,error,addedMovie,getRedirect,formData} = values;
const handleChange = name => event => {
const value = name === "photo" ? event.target.files[0] : event.target.value
formData.set(name,value); // <-
setValues({...values,[name]:value})
};
const onSubmit = (e) => {
e.preventDefault();
setValues({...values,error:'',loading:true})
addMovie(user._id,token,formData).then(data =>{
// ^^^^^^^^ <-
if(data.error){
setValues({...values,error:data.error})
}else{
setValues({
...values,
movie_name:'',
actor:'',
country_of_origin:'',
duration:'',
director:'',
photo:'',
loading:false,
addedMovie: data.movie_name
})
}
})
You might wanted to do somethig like this,
const [values,setValues] = useState({
movie_name:'',
actor:'',
country_of_origin:'',
duration:'',
director:'',
photo:'',
loading:false,
error:'',
addedMovie:'',
getRedirect:false,
})
const {movie_name,actor,country_of_origin,duration,director,photo,loading,error,addedMovie,getRedirect} = values;
const handleChange = name => event => {
const value = name === "photo" ? event.target.files[0] : event.target.value
setValues({...values,[name]:value})
};
const onSubmit = (e) => {
e.preventDefault();
setValues({...values,error:'',loading:true})
addMovie(user._id,token,JSON.stringify(values)).then(data =>{
if(data.error){
setValues({...values,error:data.error})
}else{
setValues({
...values,
movie_name:'',
actor:'',
country_of_origin:'',
duration:'',
director:'',
photo:'',
loading:false,
addedMovie: data.movie_name
})
}
})
const [values,setValues] = useState({
movie_name:'',
actor:'',
country_of_origin:'',
duration:'',
director:'',
photo:'',
loading:false,
error:'',
addedMovie:'',
getRedirect:false,
formData:new FormData() <---- declare form, data like this
})
I know it's late but according to my study,
we need to check if we are on a server-side environment or client environment (browser).
we can check(for client-side), (process.browser == true) but since now it is deprecated we can use
**(typeof window !== 'undefined')**
const [values, setValues] = useState({
formData: typeof window !== 'undefined' && new FormData(),
// other values
});
Refer to https://github.com/zeit/next.js/issues/5354#issuecomment-520305040
Also,
If you're using Next.js newer versions, you can use getStaticProps or getServerSideProps instead of getInitialProps.
My it's super simple but I get stuck.
I need to update an array on MongoDB with fetch PUT
I tested it with postman and works perfectly but my app React + Redux doesn't work
import React, { Fragment, useEffect, useState } from "react";
import PropTypes from "prop-types";
import "materialize-css/dist/css/materialize.min.css";
import M from "materialize-css/dist/js/materialize.min.js";
import config from "react-global-configuration";
import Preloader from "../layout/Preloader";
import { connect } from "react-redux";
import { getColors, updateColors } from "../../redux/actions/settingsActions";
const Settings = ({
setting: { settings, loading },
getColors,
updateColors
}) => {
const [HighPColor, setHighPColor] = useState("");
const [NormalPColor, setNormalPColor] = useState("");
const [LowPColor, setLowPColor] = useState("");
useEffect(() => {
M.AutoInit();
getColors();
//eslint-disable-next-line
}, []);
const onSubmit = () => {
const updColors = {
id: settings[0]._id,
colors: [
{
_id: colorsArray.colors[0]._id,
HighPColor,
NormalPColor,
LowPColor
}
]
};
updateColors(updColors);
M.toast({ html: "Settings updated" });
};
if (loading || settings === null) {
return <Preloader />;
}
const colorsArray = settings[0];
return (
<Fragment>
<div id="color-settings" className="container">
<div className="">
<h4>Set Priorities Colors </h4>
<div className="row">
<div>High Priority</div>
<div className="input-field">
<input
type="text"
name="highPColor"
defaultValue={colorsArray.colors[0].HighPColor}
onChange={e => setHighPColor(e.target.value)}
/>
</div>
</div>
<div className="row">
<div>Normal Priority</div>
<div className="input-field">
<input
type="text"
name="normalPColor"
defaultValue={colorsArray.colors[0].NormalPColor}
onChange={e => setNormalPColor(e.target.value)}
/>
</div>
</div>
<div className="row">
<div>Low Priority</div>
<div className="input-field">
<input
type="text"
name="lowPColor"
defaultValue={colorsArray.colors[0].LowPColor}
onChange={e => setLowPColor(e.target.value)}
/>
</div>
</div>
</div>
<div className="">
<a
href="#!"
onClick={onSubmit}
className="modal-close waves-effect blue btn"
>
Enter
</a>
</div>
</div>
</Fragment>
);
};
Settings.propTypes = {
setting: PropTypes.object.isRequired,
getColors: PropTypes.func.isRequired,
updateColors: PropTypes.func.isRequired
};
const mapStateToProps = state => ({
setting: state.settings
});
export default connect(mapStateToProps, { getColors, updateColors })(Settings);
I take everything from some inputs values that work perfectly
Redux action:
export const updateColors = colors => async dispatch => {
try {
setLoading();
const res = await fetch(`/api/settings/${colors.id} `, {
method: "PUT",
body: JSON.stringify(colors),
headers: {
"Content-Type": "application/json"
}
});
const data = await res.json();
dispatch({
type: UPDATE_COLORS,
payload: data
});
} catch ...
Redux reducer:
case UPDATE_COLORS:
return {
...state,
settings: state.settings.map(setting =>
setting._id === action.payload._id ? action.payload : setting
),
loading: false
};
it gives me back:
UnhandledPromiseRejectionWarning: TypeError: Cannot destructure property `NormalPColor` of 'undefined' or 'null'.
[0] at router.put (C:\Users\Marco\Desktop\React-Course\to-do-list\routes\settings.js:81:7)
This happens despite I commented the line 81
Any Idea of my mistakes?
thanks!
It sounds odd but now works I don't know what I have done but now updates