I assign multiple objects in one useState and then fetch the data from the database using the redux toolkit and then defined values for those objects but when I do console.log it shows me a state value is undefined but console.log the fetch data from the database is successful.
here is the code
const { data } = useGetConfigQuery();
console.log(data);
console.log(data?.mailgun_api_key);
const configData = {
mailgun_api_key: data?.mailgun_api_key,
mailgun_username: data?.mailgun_username,
mailgun_url: data?.mailgun_url,
email_id_for_mail_sent: data?.email_id_for_mail_sent,
isDiscountAvailable: data?.isDiscountAvailable,
discounted_amount: data?.discounted_amount,
min_amount_scheme_started: data?.min_amount_scheme_started,
max_amount_scheme: data?.max_amount_scheme,
razorpay_key: data?.razorpay_key,
razorpay_secret: data?.razorpay_secret,
razorpay_company_name: data?.razorpay_company_name,
};
const [edit, setEdit] = useState(false);
const [config, setConfig] = useState(configData);
console.log(config.mailgun_api_key);
console.log(config);
const handleChange = (e) => {
setConfig({ ...config, [e.target.name]: e.target.value });
};
the redux part
export const configApiSlice = apiSlice.injectEndpoints({
endpoints: (builder) => ({
getConfig: builder.query({
query: () => ({
url: `${CONFIG_API_URL}`,
method: "GET",
}),
keepUnusedDataFor: 5,
providesTags: ["Configuration"],
}),
updateConfig: builder.mutation({
query: (data) => ({
url: `${CONFIG_API_URL}`,
method: "PUT",
body: data,
credentials: "include",
}),
invalidatesTags: ["Configuration"],
}),
}),
});
>Solution :
When you initially define configData, the data object from useGetConfigQuery() might not have been populated yet, so the values will be undefined.
import { useGetConfigQuery } from 'path/to/your/apiSlice'; // Import the query hook
const MyComponent = () => {
const { data, isLoading } = useGetConfigQuery(); // Retrieve the data and loading state
const configData = {
mailgun_api_key: data?.mailgun_api_key,
mailgun_username: data?.mailgun_username,
// ... other properties
};
const [edit, setEdit] = useState(false);
const [config, setConfig] = useState(configData);
useEffect(() => {
// Update the config state when the data changes
setConfig(configData);
}, [data]);
const handleChange = (e) => {
setConfig({ ...config, [e.target.name]: e.target.value });
};
// Render loading state while fetching data
if (isLoading) {
return <div>Loading...</div>;
}
console.log(config.mailgun_api_key);
console.log(config);
return (
<div>
{/* Render your component UI here */}
</div>
);
};
export default MyComponent;