Populate my options data with react-select from API? - reactjs

This doesn't seem to be working when i try to populate my data with the data i fetched from my API. I am currently fetching the data, storing it in my array called ProductsAndAirlines which i instantiated in my constructor, then I am setting the data values dynamically in my options,but currently it doesn't. It only inserts the first static value which is PBS.
Code
getProductsAndAirlines = _ => {
fetch('http://localhost:4000/allProductAndAirlineValuesInJira')
.then(res => res.json())
.then( res =>
this.setState({ ProductsAndAirlines: res.data }
))
.catch(err => console.error(err))
}
componentDidMount() {
this.getAirlines();
this.getProductsAndAirlines();
setTimeout(() => {
this.setState({ show: true });
}, 10);
}
const optionsProduct = [
ProductsAndAirlines && ProductsAndAirlines.projects && Object.keys(ProductsAndAirlines.projects).map((issue, i) => (
ProductsAndAirlines.projects[0].issuetypes[0].fields.customfield_11600.allowedValues && Object.keys(ProductsAndAirlines.projects[0].issuetypes[0].fields.customfield_11600.allowedValues ).map((product, product_index) => (
{value: ProductsAndAirlines.projects[0].issuetypes[0].fields.customfield_11600.allowedValues[product_index].value, label: ProductsAndAirlines.projects[0].issuetypes[0].fields.customfield_11600.allowedValues[product_index].value}
))
))
render(){
<Select
placeholder = {this.state.Product}
onChange={this.handleChangeProduct}
options={optionsProduct()}
/>
}

It's, probably, because your map function is wrong somehow. If you take a deep look you can check, for each key in ProductsAndAirlines.projects, the map function is returning an entirely new array. in the end, the options are being like
[
[{ value: 'PBS', label: 'PBS' },
{ value: 'Pairing', label: 'Pairing' },
{ value: 'MPP - Insight', label: 'MPP - Insight' },
{ value: 'BLISS', label: 'BLISS' },
{ value: 'Shiftlogic', label: 'Shiftlogic'}
]],
[{ value: 'PBS', label: 'PBS' },
{ value: 'Pairing', label: 'Pairing' },
{ value: 'MPP - Insight', label: 'MPP - Insight' },
{ value: 'BLISS', label: 'BLISS' },
{ value: 'Shiftlogic', label: 'Shiftlogic'}
]]
]

Related

how can i loop through an array to generate objects

I want to loop through an array to generate a customized object array
const frequencies = [
{
value: "none",
label: "None",
},
{
value: "1_month",
label: "1 month",
},
{
value: "2_month",
label: "2 month",
},
];
const loop = {[...new Array(10)].map((_, index) => {
return [
{
value: index,'month',
label: index,'month',
},
];
})}
You're assigning a object {} to the loop variable which you then try to add a array to without a key. This is not working. When returning from the map function you return a array [].
You can use the index in a string with the `${index} month` syntax:
const loop = [...new Array(10)].map((_, index) => {
return [
{
value: `${index}_month`,
label: `${index} month`,
},
];
});
console.log(loop);

Why can't I push in <option> when I get the 'response.data'?

Why can't I push in my <option> when I get the response.data?
type State = {
companyManagerMap: null | Map<string, string[]>
}
useEffect(() => {
AdminListManager()
.then((response) => {
const { data } = response.data
console.log( { data });
setState((s) => ({
...s,
companyManagerMap: new Map(
Object.keys(data).map((key) => [key, data[key]])
),
}))
})
.catch(showUnexpectedError)
}, [showUnexpectedError])
data format
{"total":2,"data":[{"id":1,"name":"newspeed","contains_fields":[{"id":1,"name":"Official"}]},{"id":2,"name":"YAMAHA","contains_fields":[{"id":3,"name":"US"}]}]}
You are using your .map and Object.keys wrong
Look here at where you iterate over your Object keys properly :)
const data = {
total: 2,
data: [
{ id: 1, name: 'newspeed', contains_fields: [{ id: 1, name: 'Official' }] },
{ id: 2, name: 'YAMAHA', contains_fields: [{ id: 3, name: 'US' }] },
],
};
//now iterate over it properly
data.data.map((item) => {
Object.keys(item).map((key) => {
console.log(item[key]);
});
});
console.log will return this output
1
newspeed
[ { id: 1, name: 'Official' } ]
2
YAMAHA
[ { id: 3, name: 'US' } ]
I'm guessing you want to add the new data from your res.data to a state
So you can do something like this:
const fetchData = async () => {
try {
const res = await AdminListManager()
//do data manipulation over objects and set new state
} catch (error) {
showUnexpectedError()
}
}
useEffect(()=> {
fetchData()
}, [showUnexpectedError])

Handling relational data in Zustand

I need some input from people more experienced with Zustand to share their way of managing relational state. Currently we have the following:
Let's assume we have the example entities Campaign, Elementss and their Settings. The REST API returning them is in the following format:
GET <API>/campaigns/1?incl=elements,elements.settings
{
"id":1,
"name":"Welcome Campaign",
"elements":[
{
"id":5,
"type":"heading",
"label":"Heading",
"content":"Welcome!",
"settings":[
{
"id":14,
"name":"backgroundColor",
"value":"#ffffff00"
},
{
"id":15,
"name":"color",
"value":"#ffffff00"
}
]
},
{
"id":6,
"type":"button",
"label":"Button",
"content":"Submit",
"settings":[
{
"id":16,
"name":"backgroundColor",
"value":"#ffffff00"
},
{
"id":17,
"name":"color",
"value":"#ffffff00"
},
{
"id":18,
"name":"borderRadius",
"value":"3px"
}
...
]
}
...
]
}
What we are currently doing in the Reactjs app is fetching this data, then transforming it to the following normalized format and set functions:
const useCurrentCampaignStore = create(
combine(
{
campaign: {
id: 1,
name: "Welcome Campaign"
},
elements: [
{
id: 5,
campaignId: 1,
type: "heading",
label: "Heading",
content: "Welcome!"
},
{
id: 6,
campaignId: 1,
type: "button",
label: "Button",
content: "Submit"
}
],
settings: [
{
id: 14,
elementId: 5,
name: "backgroundColor",
value: "#ffffff00"
},
{
id: 15,
elementId: 5,
name: "color",
value: "#ffffff00"
},
{
id: 16,
elementId: 6,
name: "backgroundColor",
value: "#ffffff00"
},
{
id: 17,
elementId: 6,
name: "disabled",
value: false
},
{
id: 18,
elementId: 6,
name: "borderRadius",
value: 3,
}
]
},
set => ({
updateSetting: (id: string | number, newValue: string | number | boolean) =>
set(state => {
const settings = [...state.settings];
return {
...state,
settings: settings.map(setting => {
if (setting.id == id) {
return { ...setting, value: newValue };
}
return setting;
})
};
}),
updateElementContent: (id: string | number, newValue: string) => {
set(state => {
const elements = [...state.elements];
return {
...state,
elements: elements.map(element => {
if (element.id == id) {
return { ...element, content: newValue };
}
return element;
})
};
});
}
})
)
);
I am, however, not sure this is the optimal solution, because It's rather tedious transforming all GET requests to a normalized format and then converting them back to nested objects when you want to construct either a POST, PUT or PATCH request.
So, to put it short, how do you guys design the state in your Zustand-based RESTful-API-backed React apps?

How to add the two map() function(bind) and display into the page? Issue on calling two maps

In reactjs, How to add the two map() function(bind) and display into the page? Facing Issue on calling two map in reactjs
import React from "react";
import Select from "react-select";
export default class Sampletest extends React.Component {
constructor(props) {
super(props);
this.state = {
years: {
options: [
{ value: '2021', label: '2021' },
{ value: '2020', label: '2020' },
{ value: '2019', label: '2019' },
{ value: '2018', label: '2018' },
{ value: '2017', label: '2017' },
{ value: '2016', label: '2016' },
],
value: null
},
categories: {
options: [
{ value: '0', label: 'Incomplete' },
{ value: '1', label: '80G' },
{ value: '2', label: '80G' },
{ value: '3', label: 'Sports' },
{ value: '4', label: 'Social welfare' },
{ value: '5', label: 'Professional' },
{ value: '6', label: 'Health' },
{ value: '7', label: 'Food and Nutrition' },
{ value: '8', label: 'Education' }
],
value: null
},
Activity: {
options: [
{ value: '0', label :'My Causes'},
{ value: '1', label :'Liked Causes'},
{ value: '2', label :'Commented Causes'},
{ value: '3', label :'Pledged Causes'}
],
value: null
} ,
// Details:[]
};
}
onSelectChange(name, value) {
this.setState(
(prev) => {
return {
...prev,
[name]: {
...prev[name],
value: value.value
}
};
},
() => {
let url =
"http://localhost:88888/api/GetProfile/Get_MyPostDetails?id=" +
this.state.Activity.value + "&Year=" +
this.state.years.value +
"&CategoryID=" +
this.state.categories.value
;
let user = JSON.parse(localStorage.getItem("user"));
const accessToken = user;
console.log(accessToken);
//console.log("hi");
fetch(url, {
method: "GET",
headers: {
"Content-type": "application/json",
Accept: "application/json",
Authorization: "Bearer " + accessToken,
"Access-Control-Allow-Headers": "Access-Control-Request-Headers "
}
//body:JSON.stringify(data)
})
.then((response) => response.json())
.then((data) => {
this.setState({
Details: data
});
console.log("Filter", data);
// console.log(emps.profile_dateOfAnniversary);
});
}
);
}
render() {
const {Details} = this.state;
return (
<div>
{Object.keys(this.state).map((name, i) => {
return (
<Select
key={i}
placeholder={name}
options={this.state[name].options}
onChange={this.onSelectChange.bind(this, name)}
/>
);
})}
{Details.map(emp => (
<div>
<div>{emp.profile_name} </div>
</div>
))}
</div>
);
}
}
While Compile this code , Facing issue as--> TypeError: Cannot read properties of undefined (reading 'map').
I have added my code , we need to add map method in the program for output and I have use this class component and calling this page into another page and display the object into array of object.
Initialize Details as Array while declaring state.
it will be undefined on mounting face so you get the error
and check on response you are getting this response as array.

Update a selected property from react state of objects with arrays

Assume that this state has initial data like this
const [options, setOptions] = useState({
ProcessType: [
{ value: 1, label: 'Type1' }, { value: 2, label: 'Type2' }
],
ResponsibleUser: [
{ value: 1, label: 'User1' }, { value: 2, label: 'User2' }
]
});
The following function will be called again and again when a post/put called
Help me to complete the commented area as described there.
const fetchProcesses = async () => {
await axios.get(`${process.env.REACT_APP_SERVER_BASE_URL}/processes/`)
.then((result) => {
/*
I want here to clear the existing data in options.ProcessType and
map result.data as { value: result.data.id , label: result.data.name },....
and push/concat it into to options.ProcessType but i want to keep the data
inside options.ResponsibleUser unchanged.
result.data is an array of objects like this,
[
{ id: 1 , name: 'Type1', desc : 'desc1', creator: 3, status: 'active' },
{ id: 2 , name: 'Type2', desc : 'desc2', creator: 6, status: 'closed' },
.....
.....
]
*/
})
}
Here is a solution
const fetchProcesses = async () => {
await axios.get(`${process.env.REACT_APP_SERVER_BASE_URL}/processes/`)
.then((result) => {
// solution
setOptions({ResponsibleUser: [...options.ResponsibleUser], ProcessType: result.data.map(row => ({value: row.id, label: row.name}))})
})
}

Resources