I have onload api call from where I get the isMenuCreated flag and according to its value true or false, I have to display the data. but I’m getting the expected value when I refresh the page. As I can see is when I get the data and state changes but it’s not re-rendering the component.
What I have to do is when I get the data from API, I have to update the value of isMenuCreated to true or false. But I can set it on refresh.
import React, { useEffect, useState } from 'react';
import CategoryFields from './dynamic field component/CategoryFields';
import {
Button,
Form,
Space,
Select,
message,
Collapse,
Empty,
Input,
} from 'antd';
import { useLazyQuery, useMutation, useQuery } from '@apollo/client';
import {
GET_CATEGORY_ITEMS,
GET_CUISINES_CATEGORY,
GET_ITEM_VARIANTS,
GET_MENU_CUISINE,
GET_RES_BY_OWNER,
GET_VARIANT_OPTIONS,
} from '../../graphQL/Queries';
import { CREATE_RESTAURANT_MENU } from '../../graphQL/Mutation';
import { getUserId } from '../../utils/auth';
import './menuManagement.css';
import { EditFilled } from '@ant-design/icons';
const { Panel } = Collapse;
const MenuManagement = () => {
const [isCategoryEdited, setIsCategoryEdited] = useState(false);
const [isItemEdited, setIsItemEdited] = useState(false);
const [isMenuCreated, setIsMenuCreated] = useState(false);
const [restaurantId, setRestaurantId] = useState('');
const [restaurantName, setRestaurantName] = useState('');
const [userId, setUserId] = useState();
const [isLoading, setIsLoading] = useState(true);
// const [restaurantOwnerData, setRestaurantOwnerData] = useState({});
// const [defaultActivateKey, setDefaultActivateKey] = useState(null);
const {
data: restaurantOwnerData,
refetch,
loading,
} = useQuery(GET_RES_BY_OWNER, {
variables: {
ownerId: +userId,
},
});
const [getMenuCuisines, { data: cuisineData }] =
useLazyQuery(GET_MENU_CUISINE);
/******* API TO GET RESTAURANT OF LOGGED IN USER *********** */
// useEffect(() => {
// (async () => {
// const USER_ID = await getUserId();
// setUserId(USER_ID);
// })();
// }, []);
useEffect(() => {
console.log('RESDATA', restaurantOwnerData);
}, [restaurantOwnerData]);
useEffect(() => {
console.log('OUTSIDE', loading);
if (loading === false) {
console.log('LOADING-->', loading);
}
}, [loading]);
useEffect(() => {
loading === false &&
restaurantOwnerData &&
// (async () => {
// try {
console.log(
'restaurantOwnerData?.getRestaurantByOwner?.isMenuCreated: ',
restaurantOwnerData?.getRestaurantByOwner?.isMenuCreated
);
if (restaurantOwnerData?.getRestaurantByOwner?.isMenuCreated) {
console.log('set true');
setIsMenuCreated(true);
}
setRestaurantId(restaurantOwnerData?.getRestaurantByOwner?.id);
setRestaurantName(restaurantOwnerData?.getRestaurantByOwner?.name);
setIsLoading(false);
// })();
}, [loading, restaurantOwnerData]);
// useEffect(() => {
// setRestaurantId(restaurantOwnerData?.getRestaurantByOwner?.id);
// }, [restaurantOwnerData, restaurantId]);
useEffect(() => {
if (restaurantId) {
getMenuCuisines({ variables: { restaurantId: restaurantId } });
}
setUserId(getUserId());
}, [restaurantId]);
// useEffect(() => {
// setRestaurantName(restaurantOwnerData?.getRestaurantByOwner?.name);
// }, [restaurantOwnerData]);
/********** API TO CREATE RESTAURANT MENU ********* */
const [createRestaurantMenu] = useMutation(CREATE_RESTAURANT_MENU);
const createRestaurantMenuHandler = async (menuData) => {
try {
await createRestaurantMenu({
variables: {
restaurantId: restaurantId,
data: menuData.data,
},
}).then((response) => {
message.success(response?.data?.createRestaurantMenu?.message);
setIsMenuCreated(true);
refetch();
});
} catch (err) {
message.error(err);
}
refetch();
};
const CuisineIdHandler = () => {
const [getCuisineCategories, { data: cuisineCategory }] = useLazyQuery(
GET_CUISINES_CATEGORY
);
const idHandler = (value) => {
getCuisineCategories({
variables: { restaurantId: +restaurantId, cuisineId: +value },
});
};
const [getCategoryItems, { data: itemsData }] =
useLazyQuery(GET_CATEGORY_ITEMS);
const [getItemVariants, { data: variantData }] =
useLazyQuery(GET_ITEM_VARIANTS);
const [getVariantOptions, { data: optionsData }] =
useLazyQuery(GET_VARIANT_OPTIONS);
const categoryIdHandler = (values) => {
if (values) {
getCategoryItems({ variables: { categoryId: +values } });
}
};
const variantsIdHandler = (values) => {
if (values) {
getItemVariants({ variables: { itemId: +values } });
}
};
const optionIdHandler = (values) => {
if (values) {
getVariantOptions({ variables: { itemId: +values } });
}
};
return (
<Collapse accordion onChange={idHandler}>
{cuisineData?.getMenuCuisines?.cuisines?.map((cuisine) => {
return (
<Panel header={cuisine?.cuisineName} key={cuisine?.id}>
{cuisineCategory?.getCuisineCategories?.categories?.length > 0 ? (
<div className='edit-menu'>
<h1>CATEGORIES</h1>
<Button
onClick={() => {
setIsCategoryEdited(true);
// setDefaultActivateKey(cuisine?.id);
}}
className='edit-btn'
type='primary'
icon={<EditFilled />}
/>
</div>
) : (
<Empty />
)}
<Collapse accordion onChange={categoryIdHandler}>
{isCategoryEdited &&
cuisineCategory?.getCuisineCategories?.categories?.length >
0 && (
<Form>
<Form.Item className='itemPanel' label='Category Name'>
<Input />
</Form.Item>
<Form.Item className='itemPanel'>
<Button
type='primary'
htmlType='submit'
onClick={() => setIsCategoryEdited(false)}
>
Done
</Button>
</Form.Item>
</Form>
)}
{!isCategoryEdited &&
cuisineCategory?.getCuisineCategories?.categories?.map(
(category) => {
return (
<Panel header={category.categoryName} key={category.id}>
<div className='edit-menu'>
<h1>ITEMS</h1>
<Button
onClick={(e) => {
e.stopPropagation();
setIsItemEdited(true);
}}
className='edit-btn'
type='primary'
icon={<EditFilled />}
/>
</div>
<Collapse accordion onChange={variantsIdHandler}>
{isItemEdited && (
<Form>
<Form.Item
className='itemPanel'
label='Description'
>
<Input />
</Form.Item>
<Form.Item className='itemPanel' label='Price'>
<Input />
</Form.Item>
<Form.Item className='itemPanel'>
<Button
type='primary'
onClick={(e) => {
e.stopPropagation();
setIsItemEdited(false);
}}
>
Done
</Button>
</Form.Item>
</Form>
)}
{!isItemEdited &&
itemsData?.getCategoryItems?.items?.map(
(item) => (
<React.Fragment key={item.id}>
<h3 className='itemPanel'>
Description: {item.itemDescription}
</h3>
<h3 className='itemPanel'>
Price: {item.itemPrize}
</h3>
<Panel header={item.itemName} key={item.id}>
<div className='edit-menu'>
<h1>VARIANTS</h1>
<Button
className='edit-btn'
type='primary'
icon={<EditFilled />}
/>
</div>
<Collapse onChange={optionIdHandler}>
{variantData?.getItemVariants?.variants?.map(
(variant) => (
<React.Fragment key={variant.id}>
<h3 className='itemPanel'>
Description:{' '}
{variant.description}
</h3>
<h3 className='itemPanel'>
Multiple:{' '}
{variant.isMulti === 'true'
? 'Yes'
: 'No'}
</h3>
<h3 className='itemPanel'>
Required:{' '}
{variant.isRequired === 'true'
? 'Yes'
: 'No'}
</h3>
<Panel
header={variant.variantName}
key={variant.id}
>
<div className='edit-menu'>
<h1>OPTIONS</h1>
<Button
className='edit-btn'
type='primary'
icon={<EditFilled />}
/>
</div>
<Collapse>
{optionsData?.getVariantOptions?.options?.map(
(option) => (
<React.Fragment
key={option.id}
>
<h3 className='itemPanel'>
Price: {option.prize}
</h3>
<Panel
header={option.name}
showArrow={false}
></Panel>
</React.Fragment>
)
)}
</Collapse>
</Panel>
</React.Fragment>
)
)}
</Collapse>
</Panel>
</React.Fragment>
)
)}
</Collapse>
</Panel>
);
}
)}
</Collapse>
</Panel>
);
})}
</Collapse>
);
};
return loading ? (
<div style={{ width: '100%' }}>Loading</div>
) : (
<div className='main'>
{isMenuCreated ? (
<>
<h1>{restaurantName}'s Menu</h1>
<CuisineIdHandler />
</>
) : (
// restaurantOwnerData &&
<Form
initialValues={{ isRequired: false, isMulti: false }}
onFinish={(data) => createRestaurantMenuHandler(data)}
layout={{
labelCol: { span: 4 },
wrapperCol: { span: 14 },
}}
>
<>
<Form.List name='data'>
{(data, { add, remove }) => {
return (
<div>
{data.map((field) => (
<Space
className='cuisine-category-main'
key={field.key}
align='start'
>
<Form.Item
{...field}
name={[field.name, 'cuisine']}
key={field.key}
rules={[
{
required: true,
message: 'Please select any cuisine',
},
]}
>
<Select
showSearch
style={{ width: 200 }}
placeholder='Cuisine Name'
>
{cuisineData?.getMenuCuisines?.cuisines?.map(
(cuisine) => {
return (
<Select.Option
name='cuisine'
key={cuisine.id}
value={cuisine.id}
>
{cuisine.cuisineName}
</Select.Option>
);
}
)}
</Select>
</Form.Item>
<Form.Item>
<CategoryFields fieldKey={field.name} />
</Form.Item>
<Button
className='remove-btn'
type='primary'
onClick={() => {
remove(field.name);
}}
>
Remove Cuisines
</Button>
</Space>
))}
<Button
style={{ marginBottom: '10px' }}
type='primary'
onClick={() => {
add();
}}
block
>
Add Cuisine
</Button>
</div>
);
}}
</Form.List>
</>
<>
<Button block className='add-cuisine-btn' htmlType='submit'>
Submit
</Button>
</>
</Form>
)}
</div>
);
};
export default MenuManagement;