Remove asterisk from only one field - javascript

I have a custom component that takes in values from an API and then displays them to a user, however within this component I give a 'required' flag to give an asterisk to the label, however I only want one field as seen below to have an asterisk not both as is currently happening.
<Grid item xs={12} sm={6}>
<SearchUsers
name="primaryOfficerId"
label="PO Responsible"
id="primaryOfficerId"
onSelect={change.bind(null, 'primaryOfficerId')}
error={touched.primaryOfficerId && Boolean(errors.primaryOfficerId)}
/>
</Grid>
<Grid item xs={12} sm={6}>
<SearchUsers
name="supportOfficerId"
label="Support Officer"
id="supportOfficerId"
onSelect={change.bind(null, 'supportOfficerId')}
/>
</Grid>
And now my custom component
const Search = (props) => {
const [data, setData] = useState([]);
const [select, setSelect] = useState(0);
const { type: TYPE, name: NAME, label: LABEL, onSelect, filter } = props;
const applyFilter = (data) => {
let result = data;
if (filter) {
result = filter(data);
}
return result;
};
useEffect(() => {
getLookupData(TYPE)
.then((response) => {
setData(response);
})
.catch((error) => {
if (error === HttpStatus.NOT_FOUND) {
setData([]);
} else {
throw error;
}
});
}, [TYPE]);
const options = applyFilter(data).map((item) => (
<MenuItem value={item.id} key={item.id}>
{item[NAME]}
</MenuItem>
));
const handleChange = (event) => {
setSelect(event.target.value);
onSelect && onSelect(event);
};
const { classes } = props;
return (
<FormControl required className={classes.formControl} id={NAME} error={props.error}>
<FormControlLabel control={<InputLabel htmlFor={NAME}>{LABEL}</InputLabel>} />
<Select
name={TYPE}
value={select}
onChange={handleChange}
disabled={props.disabled || options.length === 0}
input={<Input name={TYPE} id={NAME} />}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
{options}
</Select>
</FormControl>
);
};
Below you can see an image of my problem, both PO, and So responsible have an asterisk. I need only PO to have this asterisk but my component does not currently allow for individuals

Simply make your component customizable by passing it a required prop as boolean then in your component make it dynamic :
<FormControl required={props.required}>
// ...
</FormControl>
So now you can use it with an asterisk <SearchUsers required /> or without <SearchUsers required={false} />

Add additional prop required to your Search component and then use it as a prop value for FormControl:
<FormControl required={props.required} />

Related

Formik field values arn't being passed from React Context

I have a Formik form that is using a progressive stepper and have multiple fields across different components, thus requiring the need to store the values in React Context. However none of the field values are being passed, so when I click submit, all values are empty strings and the validation fails. You can see on each Formik Field i am setting the value as {state.[field]}, which comes from the Context, so I believe something is going wrong here. Can anyone see what I'm doing wrong?
Thanks a lot
Here is my parent component
const AddSongPage = () => {
const { state, dispatch } = useUploadFormContext();
const initialValues = {
name: "",
};
const { mutate: handleCreateTrack } = useCreateSyncTrackMutation(
gqlClient,
{}
);
const handleSubmit = (values: any) => {
handleCreateTrack(
{
...values,
},
{
onSuccess() {
console.log("Track added succesfully");
},
}
);
};
const validate = Yup.object({
name: Yup.string().required("Song name is required"),
description: Yup.string().optional(),
});
return (
<Layout headerBg="brand.blue">
<Formik
onSubmit={(values) => handleSubmit(values)}
initialValues={initialValues}
validationSchema={validate}
>
<Form>
<Box> {state.activeStep === 1 && <Step1 />}</Box>
<Box> {state.activeStep === 2 && <Step2 />}</Box>
<Box> {state.activeStep === 3 && <Step3 />}</Box>
<Button type={"submit"}>Submit</Button>
</Form>
</Formik>
</Layout>
);
};
Here is step 1
const Step1 = () => {
const { state, dispatch } = useUploadFormContext();
const onInputChange = (e: FormEvent<HTMLInputElement>) => {
const inputName = e.currentTarget.name;
dispatch({
type: "SET_UPLOAD_FORM",
payload: {
[inputName]: e.currentTarget.value,
},
});
};
return (
<Stack spacing={4}>
<Field name={"name"}>
{({ field, form }: any) => (
<FormControl isInvalid={form.errors.name && form.touched.name}>
<Input
{...field}
onChange={onInputChange}
value={state.name}
/>
</FormControl>
)}
</Field>
<Field name={"description"}>
{({ field, form }: any) => (
<FormControl isInvalid={form.errors.name && form.touched.name}>
<Input
{...field}
onChange={onInputChange}
value={state.description}
/>
</FormControl>
)}
</Field>
</Stack>
);
};
export default Step1;

I need to filter user based on selected name

My task is I need to filter only users from the list what I am doing is I have one field called Select Name in which I have a name list so if I select any name from the list in that I have some data in that data I need to filter only users that users I need to show in another filed called username but right now what happens if I select any one name from the first field in second TextField all the data is shown but I need to show only present users in that list in handleChange function I am performing it...
export default function App() {
const AssignSearchesForm = useFormik({
initialValues: {
selectName: "",
username: []
},
onSubmit: (values) => {
console.log(values);
}
});
const handleChange = (e) => {
const selectedName = e.target.value;
const name = nameList.find((data) => data.selectName === selectedName);
const newOptions = Object.values(name).reduce((optionList, key) => {
// if(Object.keys(name) === "user"){
// optionList.push({ value: key, label: key });
// }
optionList.push({ value: key, label: key });
return optionList;
}, []);
AssignSearchesForm.setFieldValue("selectName", selectedName);
AssignSearchesForm.setFieldValue("username", newOptions);
};
console.log(AssignSearchesForm?.values?.username);
return (
<div className="App">
<Card color="primary" variant="outlined">
<Grid
sx={{
mt: 1
}}
container
direction="row"
spacing={3}
>
<Grid item xs={4}>
<TextField
sx={{ minWidth: 170 }}
select
id="outlined-basic"
label="Select Name"
name="selectName"
size="small"
onChange={handleChange}
value={AssignSearchesForm.values.selectName}
>
{nameList?.map((option) => (
<MenuItem key={option.selectName} value={option.selectName}>
{option.selectName}
</MenuItem>
))}
</TextField>
</Grid>
<Grid item xs={4}>
<TextField
sx={{ minWidth: 170 }}
select
id="outlined-basic"
label="username"
name="username"
size="small"
{...AssignSearchesForm.getFieldProps("username")}
>
{AssignSearchesForm?.values?.username.length ? (
AssignSearchesForm?.values?.username?.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.value}
</MenuItem>
))
) : (
<MenuItem disabled>Please first select name</MenuItem>
)}
</TextField>
</Grid>
<Grid item xs={4}>
<Button
onClick={() => {
AssignSearchesForm.handleSubmit();
}}
variant="contained"
>
Add
</Button>
</Grid>
</Grid>
</Card>
</div>
);
}
CodeSandBox Link
Please add this code in change handler.
const handleChange = (e) => {
const selectedName = e.target.value;
const name = nameList.find((data) => data.selectName === selectedName);
const newOptions = Object.values(name).reduce((optionList, key) => {
// if(Object.keys(name) === "user"){
// optionList.push({ value: key, label: key });
// }
if (key != null && key.toString().includes("user"))
optionList.push({ value: key, label: key });
return optionList;
}, []);
AssignSearchesForm.setFieldValue("selectName", selectedName);
AssignSearchesForm.setFieldValue("username", newOptions);
};
You need to use Object.keys with filter predicate to get only those properties.
const handleChange = (e) => {
const selectedName = e.target.value;
const name = nameList.find((data) => data.selectName === selectedName);
const newOptions = Object.keys(name).filter(f => f.match(/user\d+/)).map(f => ({ value: f, label: f }));
console.log(newOptions);
AssignSearchesForm.setFieldValue("selectName", selectedName);
AssignSearchesForm.setFieldValue("username", newOptions);
};
I've used regex to match user<any digit>. You can update that regex as per your requirement.

How to get the field values in react material ui components

This works but the when i console log the object it gives
{ "week":undefined, "name":undefined, "code":undefined }
Moreover does wrapping all the material ui component in form tag and treating the whole code as a form, is it appropriate?
here is my code:
const ExamSimulatorForm = () => {
const weekNumber = useRef();
const examSub = useRef();
const examCode = useRef();
const handleSubmit = (event) =>{
event.preventDefault()
const week = weekNumber.current.value
const subject = examSub.current.value
const code = examCode.current.value
const examSimulatorPayload = {
week:week,
subject:subject,
code:code
}
console.log(examSimulatorPayload)
}
const [code, setCode] = useState('Quiz');
const [examSubject, setExamSubject] = useState('');
const [field, setField] = useState(1)
const handleESubjectChange = (event) => {
setExamSubject(event.target.value);
};
const handleCode = (event) => {
setCode(event.target.value);
};
return (
<form >
<CardActions onSubmit={handleSubmit}>
<Grid container spacing={2} justifyContent='center' alignItems='center' direction='column'>
<Grid item>
<TextField
InputProps={{
inputProps: {
max: 12, min: 1
}
}}
label='Week'
type='number'
onChange={(event)=>setField(parseInt(event.target.value))}
style={{minWidth:250}}
ref = {weekNumber}
required
/>
</Grid>
<Grid item>
<FormControl style={{minWidth:250}}>
<InputLabel>Subject</InputLabel>
<Select
value={examSubject}
onChange={handleESubjectChange}
ref={examSub}
required
>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item>
<FormControl style={{minWidth:250}}>
<InputLabel id="exam-code" >Exam Code</InputLabel>
<Select
labelId="exam-code"
id="exam-code-select"
value={code}
onChange={handleCode}
ref={examCode}
required
>
<MenuItem value={'Q'}>Q</MenuItem>
<MenuItem value={'M'}>M</MenuItem>
<MenuItem value={'F'}>F</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item>
<Button variant='contained' color='primary' style={{marginTop:94}} >Take Exam</Button>
</Grid>
</Grid>
</CardActions>
</form>
)
}
export default ExamSimulatorForm;
I have a similar form for attendance simulation, attendance dataset generation and exam dataset generation
I think this is good for you.
Please try this.
const ExamSimulatorForm = () => {
const [state, setState] = useState({
code: 'Quiz',
subject: '',
week: 1
});
const handleSubmit = (event) =>{
event.preventDefault()
const examSimulatorPayload = state;
console.log(examSimulatorPayload)
}
const handleChange = (evt, name) {
const { value } = evt.target;
setState({
...state,
[name]: value
});
}
return (
<form onSubmit={handleSubmit}>
<CardActions>
<Grid container spacing={2} justifyContent='center'
alignItems='center' direction='column'>
<Grid item>
<TextField
InputProps={{
inputProps: {
max: 12, min: 1
}
}}
label='Week'
type='number'
value={state.week}
onChange={(event)=>handleChange( event, "week")}
style={{minWidth:250}}
required
/>
</Grid>
<Grid item>
<FormControl style={{minWidth:250}}>
<InputLabel>Subject</InputLabel>
<Select
value={state.subject}
onChange={(event)=>handleChange( event, "subject")}
required
>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item>
<FormControl style={{minWidth:250}}>
<InputLabel id="exam-code" >Exam Code</InputLabel>
<Select
labelId="exam-code"
id="exam-code-select"
value={state.code}
onChange={(event)=>handleChange( event, "code")}
required
>
<MenuItem value={'Q'}>Q</MenuItem>
<MenuItem value={'M'}>M</MenuItem>
<MenuItem value={'F'}>F</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item>
<Button variant='contained' color='primary' style=
{{marginTop:94}} >Take Exam</Button>
</Grid>
</Grid>
</CardActions>
</form>
)
}
export default ExamSimulatorForm;
Please check it above code, and let me know your idea.
State updates in react are asynchronus, which means they don't occur as soon as you call them. You have to wait until the state updates to console.log because otherwise, nothing has changed and you are getting the initial value. You could do something like this:
useEffect(() => {
const subject = examSub.current.value
console.log(subject)
}, [examSubject])
useEffect() executes an action every time a state changes. Notice how at the end there is an array, with [examSubject]. This signifies the state that will trigger the effect. So when examSubject changes (when you assign a value to it), the effect will execute (in this case, it will log the subject).
When writing code, at least in my case, you don't need to worry about this. You can chnage the state and write your code as normal, but react might take a second or two to update the state. The only time I really notice this is when I console.log.
You can define the state for your inputs :
const [code, setCode] = React.useState('');
const [subject, setSubject] = React.useState('');
const [week, setWeek] = React.useState('');
const setExamCode = event => {
setCode(event.target.value);
};
const setSubject = event => {
setSubject(event.target.value);
};
const setWeek = event => {
setWeek(event.target.value);
};
Then call these methods from onChange event like : onChange={setExamCode} or {setSubject}
In case you want to handle data from single event and defining it's initial state try below approach :
const initialData = Object.freeze({
code: "",
subject: "",
week: ""
});
const [data, updateData] = React.useState(initialData );
const handleChange = (e) => {
updateData({
...data,
[e.target.name]: e.target.value
});
};
const handleSubmit = (e) => {
e.preventDefault()
console.log(data);
};
Then call these methods from onChange event like onChange={handleSubmit}

I use useState hock to store the value but it did not update

I am new to Reactjs
I am trying to build an address form with 3 Select ( country, State, City )
I used React hock
so when the page first load it will fetch countries list to country select after that when user select country it will fetch states list to state select and after that when user select state it will fetch cities list to city select
my issue with state hock I store the value of the user selected in the state but it did not update the value in the state in many locations I keep getting " undefined " like when the page load I get countries list as an array and I get the first country in the list as the default select item in country select but I still get keep getting " undefined " I tried many ways but still getting the same result and bellow is my code
import React,{ useEffect , useState , useCallback } from 'react';
import { InputLabel, Select , MenuItem , Grid , Typography } from '#material-ui/core';
import { useForm, FormProvider } from 'react-hook-form';
import CityHandler from 'countrycitystatejson';
export const TempAddresForm = () =>
{
const methods = useForm();
const [countries, setCountries] = useState([]);
const [countryCode, setCountryCode] = useState('');
const [country, setCountry] = useState('');
const [states, setStates] = useState([]);
const [stateName, setStateName] = useState('');
const [cities, setCities] = useState([]);
const [city, setCity] = useState('');
const fetchCounters = () => {
setCountries(CityHandler.getCountries());
setFirstCountry();
};
const countryChangeHandler = (event) => {
let tempCountryCode = event.target.value;
setCountry(CityHandler.getCountryByShort(tempCountryCode));
setCountryCode(tempCountryCode);
fetchStates(tempCountryCode);
setCities([]);
}
const fetchStates = (countryCode) =>
{
setStates(CityHandler.getStatesByShort(countryCode));
}
const stateChangeHandler = (even) =>
{
let tempState = even.target.value;
setStateName(even.target.value);
fetchCities(tempState);
}
const fetchCities = (stateName) => {
let tempCities = CityHandler.getCities(countryCode, stateName);
setCities(tempCities);
};
const cityChangeHandler = (event) =>
{
let tempCity = event.target.value;
setCity(tempCity);
console.log("Temp City Name : " + tempCity)
console.log("City Name : " + city)
}
const setFirstCountry = useCallback( () =>
{
if(countries)
{
let firstCountry = CityHandler.getCountries()[0];
console.log ("[setFirstCountry] : First Country " + JSON.stringify(firstCountry.name));
setCountry(firstCountry);
console.log ("[setFirstCountry] : Country name " + JSON.stringify(country.name));
}
}, []);
useEffect(() => {
fetchCounters();
//setFirstCountry();
}, []);
return (
<>
<Typography variant="h6" gutterBottom>Shipping Address</Typography>
<FormProvider {...methods}>
<form onSubmit={''}>
<Grid container spacing={3}>
<Grid item xs={12} sm={6}>
<InputLabel>Country</InputLabel>
<Select value={country.name} fullWidth onChange={(event) => {countryChangeHandler(event)}}>
{countries.map((countryLoop) => (
<MenuItem key={countryLoop.shortName} id={countryLoop.shortName} value={countryLoop.shortName}>
{countryLoop.name}
</MenuItem>
))}
</Select>
</Grid>
<Grid item xs={12} sm={6}>
<InputLabel>State</InputLabel>
<Select value={stateName} fullWidth onChange={(event) => {stateChangeHandler(event)}}>
{states.map((state, index) => {
return(
<MenuItem key={index} id={state} value={state}>
{state}
</MenuItem>
);
})}
</Select>
</Grid>
<Grid item xs={12} sm={6}>
<InputLabel>City</InputLabel>
<Select value={city} fullWidth onChange={(event) => {cityChangeHandler(event)}}>
{cities.map((city, index) => {
return(
<MenuItem key={index} id={city} value={city}>
{city}
</MenuItem>
);
})}
</Select>
</Grid>
</Grid>
</form>
</FormProvider>
</>
)
}
export default TempAddresForm;
if anyone could help me with this
*Note: I use this package to get the Country list countrycitystatejson
country is actually always updating but you are logging it in a useCallback hook and did not add country to its dependency array. So it only captures the initial value of country which is an empty string "" and JSON.stringify("".name) is undefined. If you add country to the dependency array of useCallback you will see it updating.
console.log( JSON.stringify("".name) )
You don't need to use useCallback here. Read this article to understand where and when to use useCallback and useMemo
The main problem is that you are mapping your country Select to country.name but your select options have country.shortName as their value - Try changing the Select value to country.shortName.
Also, you have too many state variables that are interdependent to each other. Here moving all your state variables to a single state object will make it a little bit easier to handle.
Ex Like below
{
countries: [...],
states: [...],
cities: [...],
stateName: "..",
...
...
}
countries is always constant & states, cities are just derived values. So your actual state just needs these 3 values countryShortCode, stateName and city.
Here is a snippet with all the above-mentioned changes
import React, { useState } from "react";
import {
InputLabel,
Select,
MenuItem,
Grid,
Typography
} from "#material-ui/core";
import { useForm, FormProvider } from "react-hook-form";
import CityHandler from "countrycitystatejson";
// This countriesList doesn't change so it can just be a constant outside your component
const countriesList = CityHandler.getCountries();
// Your initial state
const initialState = {
countryShortName: countriesList[0].shortName,
stateName: "",
city: ""
};
const TempAddresForm = () => {
const methods = useForm();
const [state, setState] = useState(initialState);
const changeCountry = (e) => {
setState((prevState) => ({
...prevState,
countryShortName: e.target.value,
stateName: "",
city: ""
}));
};
const changeState = (e) => {
setState((prevState) => ({
...prevState,
stateName: e.target.value,
city: ""
}));
};
const changeCity = (e) => {
setState((prevState) => ({
...prevState,
city: e.target.value
}));
};
// Derive both states and cities here ( No need to store it in state :) )
const states = CityHandler.getStatesByShort(state.countryShortName);
const cities = state.stateName
? CityHandler.getCities(state.countryShortName, state.stateName)
: [];
return (
<>
<Typography variant="h6" gutterBottom>
Shipping Address
</Typography>
<FormProvider {...methods}>
<form onSubmit={() => console.log("Submitted")}>
<Grid container spacing={3}>
<Grid item xs={12} sm={6}>
<InputLabel>Country</InputLabel>
<Select
value={state.countryShortName || ""}
fullWidth
onChange={changeCountry}
>
{countriesList.map((countryLoop) => (
<MenuItem
key={countryLoop.shortName}
id={countryLoop.shortName}
value={countryLoop.shortName}
>
{countryLoop.name}
</MenuItem>
))}
</Select>
</Grid>
<Grid item xs={12} sm={6}>
<InputLabel>State</InputLabel>
<Select value={state.stateName} fullWidth onChange={changeState}>
{states.map((state, index) => {
return (
<MenuItem key={index} id={state} value={state}>
{state}
</MenuItem>
);
})}
</Select>
</Grid>
<Grid item xs={12} sm={6}>
<InputLabel>City</InputLabel>
<Select value={state.city || ""} fullWidth onChange={changeCity}>
{cities.map((city, index) => {
return (
<MenuItem key={index} id={city} value={city}>
{city}
</MenuItem>
);
})}
</Select>
</Grid>
</Grid>
</form>
</FormProvider>
</>
);
};
export default TempAddresForm;
Comment if you need to understand anything else

State is empty even have setted up with data

I am trying to fetch the data from the database and storing it in a state but when I console log my state, no data has been stored in the state but when I console the data itself, it returns what I expected to have. This is my code;
import React, { useContext, useEffect, useState } from 'react';
import { Field, Form, Formik, useField } from 'formik';
import * as Yup from 'yup';
import {
Button,
Box,
makeStyles,
Grid,
Typography,
Divider,
FormHelperText,
Select,
MenuItem,
InputLabel,
FormControl,
} from '#material-ui/core';
import {
MuiPickersUtilsProvider,
KeyboardDateTimePicker,
} from '#material-ui/pickers';
import DateFnsUtils from '#date-io/date-fns';
import 'date-fns';
// Yup validation Schema
const validationSchema = Yup.object().shape({
date: Yup.date().required('Please enter valid date').nullable(),
teamOne: Yup.string().required('Please select team'),
teamTwo: Yup.string().required('Please select team'),
});
// This is a custom date field using Formik
const DateTimeField = ({ field, form, ...props }) => {
const currentError = form.errors[field.name];
return (
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDateTimePicker
clearable
disablePast
name={field.name}
value={field.value}
format="MM/dd/yyyy"
helperText={currentError}
error={!!currentError}
onError={(error) => {
if (error !== currentError) {
form.setFieldError(field.name, error);
}
}}
onChange={(date) => form.setFieldValue(field.name, date, true)}
{...props}
/>
</MuiPickersUtilsProvider>
);
};
// Custom <Select> field
const TeamSelection = ({ name, ...props }) => {
const [field, meta] = useField(name);
const errorText = meta.error && meta.touched ? meta.error : '';
return (
<>
<Select
name={field.name}
{...field}
fullWidth
error={!!errorText}
{...props}
>
{props.children}
</Select>
<FormHelperText error>{errorText}</FormHelperText>
</>
);
};
export default function AddMatch() {
const classes = useStyles();
const fetchContext = useContext(FetchContext);
const [team, setTeam] = useState([]);
useEffect(() => {
const getTeam = async () => {
try {
const { data } = await fetchContext.authAxios.get('get-all-teams');
setTeam(data);
} catch (error) {
console.log(error);
}
};
getTeam();
}, [fetchContext]);
console.log(team);
return (
<Formik
initialValues={{ date: new Date(), teamOne: '', teamTwo: '' }}
validationSchema={validationSchema}
onSubmit={(values) => {
if (values.teamOne === values.teamTwo) {
return console.log('Teams must not be the same!');
}
return console.log(values);
}}
>
{() => (
<Form noValidate>
<Grid>
<Typography>
Add Match
</Typography>
</Grid>
<Divider />
<Box>
<Grid>
<Grid>
<Field
name="date"
label="Set date and time"
component={DateTimeField}
/>
</Grid>
<Grid>
<Grid>
<FormControl>
<InputLabel>
Team A
</InputLabel>
<TeamSelection name="teamOne">
<MenuItem value=""> </MenuItem>
{team.map((item) => (
<MenuItem value={item.teamName} key={item._id}>
{item.teamName}
</MenuItem>
))}
</TeamSelection>
</FormControl>
</Grid>
<Grid>
<FormControl>
<InputLabel>
Team B
</InputLabel>
<TeamSelection name="teamTwo">
<MenuItem value=""> </MenuItem>
{team.map((item) => (
<MenuItem value={item.teamName} key={item._id}>
{item.teamName}
</MenuItem>
))}
</TeamSelection>
</FormControl>
</Grid>
</Grid>
<Box>
<Button type="submit">
Submit
</Button>
</Box>
</Grid>
</Box>
</Form>
)}
</Formik>
)}
I'm using Material UI and Formik.
It only logged an empty array "[]" or it makes an error, (.map is not a function). I tried to set the state as an Object but there is still no data being stored with the state.
Check the post request in your res.status(200).json() or res.send() or res.json(). Don't use brackets inside .json() or .send(), in your res or response, for example:
.json({}) // Don't use brackets if you don't want to send your data as an Object
If ever you want it to be object, then call the array which is called data like
useEffect(() => {
const getTeam = async () => {
try {
const { teamsData } = await fetchContext.authAxios.get('get-all-teams');
setTeam(teamsData.data);
} catch (error) {
console.log(error);
}
};
getTeam();
}, [fetchContext]);
destructure the teamsData if you have passed it as an Object on purpose.

Categories

Resources