{ _id: 5d8b8,
given_name: 'Abi',
family_name: 'Abi',
email: 'AAA#jwt.org',
password:'password'
}
I have this data and I want to get only email.
const url = 'http://localhost:9098/api/users'
const [users, setUsers] = useState([])
useEffect(() => {
axios.get(url).then(json => setUsers(json.data))
}, [])
const getEmail = () => {
return users.map(user => {
return (
<option> {user.email} </option>
)
})
}
<select onChange={handleAddMessage}
value={message.sender}
name="sender" id="sender"required>
<option>{getEmail()} </option>
</select>
This is how I am trying to do it .I need an easy way to extract email from this data into
I think that the value attribute has to be inside the option tag.As i can see you are rendering an option tag inside an option tag because the getEmail is returning a option tag:
<option>{getEmail()} </option>
So the approcach that i came up is to make a method that renders the options based on your list:
this.renderEmails = ( ) => {
let optionList = users.map(user => {
return (
<option value={ user.email }> {user.email} </option>
)
})
return optionList
};
And in your render method:
<select onChange={handleAddMessage}
name="sender" id="sender"required>
{ this.renderEmails() }
</select>
Extract the email when you get the data. Itterate through the data using forEach and store it to a variable and finally set it to the users-state
Later you can use users.map() to display the email ID
const url = 'http://localhost:9098/api/users';
const [users, setUsers] = useState([]);
useEffect(() => {
axios.get(url).then(json => {
let usersResponse = []; json.data.forEach((data) => {
usersResponse.push(data.email);
});
setUsers(usersResponse)
})
}, []);
< select
onChange = { handleAddMessage }
value = { message.sender }
name = "sender" id = "sender" required
>
{
users.map((email) => {
<option>{email} </option>
})
}
</select >
Related
When using the parameter defaultValue of the component Select no values is found.
<Select
mode='multiple'
allowClear
style={{ width: '100%' }}
placeholder='Sélectionner...'
onChange={setValue}
onSelect={handleSelect}
defaultValue={dataChecked}
onDeselect={handleDeselect}
>
{
dataType.map((v) => (
<Option key={v.valueKey} value={v.valueKey}>
<img className='img-step' src={`http://localhost:2023/api/pictures/${props.typeUrlPicture}/${v.picture}`} alt={v.picture}/>
{" "}{v.label}
</Option>
))
}
</Select>
Here I use dataChecked as a variable. dataChecked is a array of value.
const [ data, setData ] = useState([])
const dataType = data.map((l)=> ({ label: l.name, value: l.picture, valueKey: l.id, picture: l.picture }))
const [ value, setValue ] = useState([])
const [ dataChecked, setDataChecked ] = useState([])
useEffect(() => {
fetch(`${baseUrl}/properties?type=${props.type}`)
.then((res) => res.json())
.then((data) => {
setData(data)
})
fetch(`${baseUrl}/steps/${props.idBdd}`)
.then((res) => res.json())
.then((data) => {
data.properties.filter(d => d.type === props.type).map((d) => (
setDataChecked(current => [...current, d.id])
))
})
return () => {
setData([])
setDataChecked([])
}
}, [props.type, props.idBdd])
The values of my Options are indeed integers like the values of my dataChecked array.
If I replace dataChecked with an array : [1,9]. I get my initial values. And
when I console.log(dataChecked) I get an array of [1,9] for example but my component gets no initial value.
There are two ways, you can try.
<!-- 1. Use value prop -->
<Select mode="multiple" value={defaultValue}></Select>
<!-- 2. Set defaultValue to key -->
<Select mode="multiple" key={defaultValue.join(',')}></Select>
My sorting is working but sometimes my data doesnot change as I select the option no change occurs , I guess I am not using useEffect correctly So I want what am I doing wrong , I am very confused
const { data: property, isFetching, refetch } = useQuery(['PropertySearch', startDate, endDate, where, adultCount, childCount], propertyAvaibility, {
retry: false,
enabled: !!data
})
useEffect(() => {
const sortArray = type => {
const types = {
number_of_bars: 'number_of_bars',
starting_price: 'starting_price',
};
const sortProperty = types[type];
const sorted = property?.sort((a, b) => b[sortProperty] - a[sortProperty]);
setData(sorted);
};
sortArray(sortType);
}, [sortType]);
<select onChange={(e) => setSortType(e.target.value)} className="form-control">
<option value="number_of_bars">number_of_bars</option>
<option value="starting_price">starting_price</option>
</select>
{
property?.map((item) => (
<PropertyCard
key={item?.id}
title={item?.title}
image={item?.cover_image?.url}
location={item.address}
displayFooter={false}
displayButton={false}
rating={true}
item={item}
type={item?.brand_name}
link="property">
{item?.description?.slice(0, 150)}
</PropertyCard>
))
}
I think your problem is you're using property?.map which is always referred to your original list.
For a possible fix, you could modify it to data?.map which is your sorted list.
And you also need to set a default value for data
const [data, setData] = useState(property); //`property` is from your fetched data
Full change can be
const { data: property, isFetching, refetch } = useQuery(['PropertySearch', startDate, endDate, where, adultCount, childCount], propertyAvaibility, {
retry: false,
enabled: !!data
})
const [data, setData] = useState(property); //set `property` as your default data
const [sortType, setSortType] = useState('rating');
useEffect(() => {
const sortArray = type => {
const types = {
number_of_bars: 'number_of_bars',
starting_price: 'starting_price',
};
const sortProperty = types[type];
const sorted = property?.sort((a, b) => b[sortProperty] - a[sortProperty]);
setData(sorted);
};
sortArray(sortType);
}, [sortType]);
const displayedData = data?.length ? data : property //check if data is available
<select onChange={(e) => setSortType(e.target.value)} className="form-control">
<option value="number_of_bars">number_of_bars</option>
<option value="starting_price">starting_price</option>
</select>
{
displayedData?.map((item) => ( //the main change is here
<PropertyCard
key={item?.id}
title={item?.title}
image={item?.cover_image?.url}
location={item.address}
displayFooter={false}
displayButton={false}
rating={true}
item={item}
type={item?.brand_name}
link="property">
{item?.description?.slice(0, 150)}
</PropertyCard>
))
}
I have data in dropdown now I want to filter city as per selected state, how can I do this in reactJs?
Giving Error:-
API Response:-
My code:-
function setSelectedOption(e) {
console.log(e.target.value);
let selectedState = e.target.value;
}
function GetEgyptStates() {
const [egyptData, setEgyptData] = React.useState(null);
React.useEffect(() => {
axios
.get("http://localhost:3000/states-and-districts.json")
.then((response) => {
setEgyptData(response.data);
console.log(response.data)
});
}, []);
if (!egyptData) return null;
return (
<div>
<select onChange={setSelectedOption}>
<option> -- Select State -- </option>
{Object.entries(egyptData.Egypt).map(([key, val]) => (
<option>{key}</option>
))}
</select>
<select>
<option> -- Select City -- </option>
{egyptData.Egypt.selectedState.map((state) => (
<option>{state}</option>
))}
</select>
</div>
);
}
ThankYou for your efforts!
Your setSelectedOption function does not set state to update the UI
For the fix,
You should introduce
const [selectedState, setSelectedState] = useState()
And add it to setSelectedOption
function setSelectedOption(e) {
console.log(e.target.value);
let selectedState = e.target.value;
setSelectedState(selectedState)
}
By the way, egyptData.Egypt.selectedState does not exist in your current code too, you should use egyptData.Egypt[selectedState]
{egyptData.Egypt[selectedState].map((state) => (
<option>{state}</option>
))}
I think this code can help you
**If you want get property with string name you can use setEgyptData[selectedState]
function GetEgyptStates() {
const [egyptData, setEgyptData] = React.useState();
const [cities,setCities]=React.useState([]);
const [selState,setselState]=React.useState([]);
const [selcity,setselcity]=React.useState([]);
function setSelectedOption(e) {
console.log(e.target.value);
let selectedState = e.target.value;
setselState(selectedState)
setCities(setEgyptData[selectedState])
}
React.useEffect(() => {
const fetchData=async ()=>{
let response =await axios
.get("http://localhost:3000/states-and-districts.json");
setEgyptData(response.data);
}
if(!egyptData)
fetchData();
}, [egyptData]);
if (!egyptData) return null;
return (
<div>
<select value={selState} onChange={setSelectedOption}>
<option> -- Select State -- </option>
{Object.entries(egyptData.Egypt).map(([key, val]) => (
<option key={key}>{key}</option>
))}
</select>
<select value={selcity} onChange={({target})=>setselcity(target.value)}>
<option> -- Select City -- </option>
{cities.map((city) => (
<option key={city}>{city}</option>
))}
</select>
</div>
);
}
seems egyptData.Egypt.selectedState is undefine like #Bravo said
you can do it like egyptData.Egypt.selectedState && egyptData.Egypt.selectedState.map() or egyptData?.Egypt?.selectedState?.map()
it seems like it renders before data your set method call (useEffect)
instead of doing this if (!egyptData) return null try if (!egyptData) return <></>
if you create variable with let it will only access in that block in you're code selectedState only use in setSelectedOption function you have to create state to declare as a global variable
function GetEgyptStates() {
const [egyptData, setEgyptData] = React.useState(null);
const [selectedState , setselectedState] = React.useState('');
function setSelectedOption(e) {
console.log(e.target.value);
setselectedState(e.target.value)
}
React.useEffect(() => {
axios
.get("http://localhost:3000/states-and-districts.json")
.then((response) => {
setEgyptData(response.data);
console.log(response.data)
});
}, []);
if (!egyptData) return null;
return (
<div>
<select onChange={(e)=>setSelectedOption(e)}>
<option> -- Select State -- </option>
{Object.entries(egyptData.Egypt).map(([key, val]) => (
<option>{key}</option>
))}
</select>
<select>
<option> -- Select City -- </option>
{egyptData?.Egypt[selectedState]?.map((state) => (
<option>{state}</option>
))}
</select>
</div>
);
}
This is working fine now...
Code given below:-
function GetEgyptStates() {
const [egyptData, setEgyptData] = React.useState(null);
const [cities, setCities] = React.useState([]);
const [state, selState] = React.useState();
function setSelectedOption(e) {
let state = e.target.value;
setCities(egyptData.Egypt[state]);
}
React.useEffect(() => {
const fetchData = async () => {
axios
.get("http://localhost:3000/states-and-districts.json")
.then((response) => {
setEgyptData(response.data);
console.log(response.data);
});
};
fetchData();
}, []);
if (!egyptData) return null;
return (
<div>
<select value={state} onChange={setSelectedOption}>
<option> -- Select State -- </option>
{Object.entries(egyptData.Egypt).map(([key, val]) => (
<option>{key}</option>
))}
</select>
<select>
<option> -- Select City -- </option>
{cities.map((city) => (
<option>{city}</option>
))}
</select>
</div>
);
}
Thank you all of you for your support!
I am adding all is needed to create a post, but am getting an error message saying "Facility must exist."
For some reason, the facility_id is capturing the name of the facility and not the ID.
I am setting state for facilities, and mapping / filtering for my dropdown. Please see below:
function AddPostForm({ posts, handlePost})
{
const [facilities, setFacilities] = useState ([])
const [procedures, setProcedures] = useState ([])
const uniques = procedures.map(procedure => procedure.procedure)
.filter((value, index, self) => self.indexOf(value) === index )
// console.log("unique procedures:", uniques)
const uniqFacility = facilities.map(facility => facility.name).filter((value,index, self) => self.indexOf(value) === index)
useEffect(() => {
fetch(`/posts/${procedures}`)
.then((r) => r.json())
.then(setProcedures);
}, []);
useEffect(() => {
fetch("/facilities")
.then((r) => r.json())
.then(setFacilities);
}, []);
const [formData, setFormData] = useState({
facility_id: "",
procedure:'',
date_of_procedure:'',
date_of_invoice:'',
patient_cost: "",
insurance_cost: "",
comments: ""
})
const { id } = useParams();
function handleChange(event) {
setFormData({
...formData,[event.target.name]: event.target.value,
});
}
function handleSubmit(event) {
event.preventDefault();
handlePost(formData)
return (
<div >
<form onSubmit={handleSubmit}>
<label htmlFor="facility_id">Facility:</label>
<select
id="facility_id"
name="facility_id"
value={formData.facility_id}
onChange={handleChange} >
<option value="">Select Facility</option>
{uniqFacility.map((facility) => (
<option key={facility.id} value={facility.name}>
{facility}
</option>
))}
</select>
</form>
</div>
);
}
export default AddPostForm;
When I check params in the byebug I see facility_id=>"Name of Facility", and get an error message saying that Facility must exist. I tried adjusting the map / filter function to ...facility => facility.id).filter ... , which ends up giving me the facility_id and creates the post as if the name of the entity was its id.
I think I need to adjust the map/filter formula, but I do not know how. Appreciate if someone help me out here.
How should I disable specific options from react-select isMulti based on the condition provided.
import Select from 'react-select'
const Systems = () => {
const [dataSystems, setdataSystems] = useState([])
const [systemDetails, setsystemDetails] = useState({
SYSTEMID: 1,
......
})
const getSystems = async() => {
await axios.get('/API')
.then(response => {
setdataSystems(response.data)
})
}
const [multiSelected, setmultiSelected] = useState();
var handleMultiSelect = (e) => {
setmultiSelected(Array.isArray(e)?e.map(x=> x.value):[]);
}
const bodyInsertDepSystem = (
.......
<Select
isMulti
options = {dataSystems.map(e => ({ label: e.SYSTEMALIAS, value: e.SYSTEMID }))}
onChange = {handleMultiSelect} > </Select>
)
}
What I want to do is to remove the disable the SYSTEMID from the dropdown that has same ID as systemDetails.SYSTEMID.
Hope that you can help me with this.
What I really doing on this: During edit I want to relate one SYSTEMID to multiple SYSTEMID but I want to disable or remove that has same SYSTEMID
<Select
isMulti
options = {dataSystems.map(e => ({
label: e.SYSTEMALIAS,
value: e.SYSTEMID
isDisabled: e.SYSTEMID == systemDetails.SYSTEMID ? true: null
}))}
onChange = {handleMultiSelect}>
</Select>