I am new to react and currently working on a project.
I usually use Class Components, however, I am trying to learn Functional Components but I encounter an issue with the setState.
My Component:
function GetCustomerDetailsFc(this: any, props: CustomerModel): JSX.Element {
const [state, setState] = useState('');
async function send(){
try {
const response = await axios.get<CustomerModel>(globals.urls.customerDetails)
store.dispatch(oneCustomerAction(response.data));
console.log(response.data)
setState( {customer: response.data});
} catch (err) {
notify.error(err);
}
}
useEffect(() => {
send();
});
return (
<><h1>{this.state.customer.email}</h1></>
);
}
export default GetCustomerDetailsFc;
I am not sure on how to save state so I can read it. when I log the request I can see the back-end actually returns data which contains:
User details : (id, email, password , etc...)
An Array of Coupons linked to users purchase.
so basically I can see the request responds properly, however, since I am new I am not sure exactly about the syntax and how I could read properly the data.
Customer Model:
class CustomerModel {
public id: number;
public firstName :string;
public lastName :string;
public email: string;
public token: string;
public password: string;
}
export default CustomerModel;
Note:: I use redux for this project and store data accordingly.
Thanks.
If the returned data is intended to be used locally in this component, then what you pass into useState should match the response you are receiving from the server.
So if for instance your server returns a CostomerModel object, you should initiate your useState with an object -
const [ customer, setCustomer ] = useState({})
try{
const response = await axios.get<CustomerModel>(globals.urls.customerDetails)
...
setCustomer(response);
...
}