Delete objects in Array in sequence but first one - reactjs

I'm trying to remove objects in the array from the end in sequence So I tried to use pop and splice
but for some reason, when I use the pop function then all the objects are removed, and got an error :
is not a function and when I use the splice function then all the objects are removed
here is my code :
const [appendChartData, setAppendChartData] = useState(chartData.datasets);
const appendAxis = e => {
e.preventDefault();
setAppendChartData([...appendChartData, AppendData]);
};
const deleteAxis = () => {
setAppendChartData(appendChartData.splice(-1, 1));
/// setAppendChartData(appendChartData.pop());
};
chartData.datasets
export let chartData =[ {
labels: defaultLabels,
datasets: [
{
label: "dataSetting",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
},]
AppendData
export let AppendData = {
label: "dataSetting",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
};
so I'd like to remove the array in sequence from the end

The way you used the state is wrong. You should use the chartData as state:
const [appendChartData, setAppendChartData] = useState(chartData);
const appendAxis = e => {
e.preventDefault();
setAppendChartData({
...appendChartData,
datasets: [
...appendChartData.datasets,
AppendData
]
});
};
const deleteAxis = () => {
setAppendChartData({
...appendChartData,
datasets: appendChartData.datasets.splice(-1, 1)
});
};
Also, be careful about your chartData since I saw that you defined it as an array of objects. If that's true then you must consider it in the code above.

Related

React: check if a data is duplicated in a map to ignore it

Is there any way to know if a data is repeated within a map? For example:
newArray = [name: "Jose", name:"Pedro", name:"Jose", name:"Ramon"]
newArray.map((questmapn: any, index: any) => ({questmapn.name}))
I need to know if questmapn.name is repeated inside the loop to create a ternary that doesn't show the duplicates. Is there a simplified way?
You can use onlyUnique function like below:
const newArray = [
{ name: "Jose" },
{ name: "Pedro" },
{ name: "Jose" },
{ name: "Ramon" }
];
function onlyUnique(repeatedArray) {
const names = [];
const uniqueArray = [];
repeatedArray.forEach((item) => {
if (!names.includes(item.name)) {
names.push(item.name);
uniqueArray.push(item);
}
});
return uniqueArray;
}
const uniqueArray = onlyUnique(newArray);
Note: Pass repeated array to this function and returned value will be unique based on name property.

Return in tabular format in reactjs

I'm new to web dev and currently trying to develop a dashboard.
My api data returns like this:
{
'ada': {'available': '45', 'profit': '-0.5'},
'eth':{'available': '2', 'profit': '5'}
}
and the code that gets the data is
useEffect(() => {
const fetchAPI = async() => {
const resp = await httpClient.get("//localhost:5000/dashboard")
data = resp.data
console.log(data)
if(data){
keys_list = Object.keys(data).map((crypto) => crypto)
data_list = Object.values(data).map((crypto) => crypto.current)
setChartData({
labels: keys_list,
datasets: [
{
label: 'Price in KRW',
data: data_list,
backgroundColor: [
"#ffbb11",
"#ecf0f1",
"#50AF95",
"Blue",
"Purple",
"Red",
"Green"
]
}
]
});
}
};
fetchAPI()
}, []);
const [chartData, setChartData] = useState({datasets: []})
I would like to make a sort of table that just returns the different values of each keys.
token available profit
ada 45 -0.5
eth 2 5
Any insights would be highly appreciated

Typing a function that can accept/return N array of items with rest/spread generics?

We have a lot of arrays that store objects of key/value pairs for dropdowns and other items in our app.
We also use next-i18next for our translations and I'm trying to create a helper function that can receive 1...n of these, transform the values to use the translation function and destructure them in a single line, as opposed to calling the hook multiple times
type OptionType = { text: string, value: string };
const untransformedMap1: OptionType[] = [
{ text: 'settings:preferences', value: 'preferences' },
{ ... }
];
// eg:
const [map1, map2, ...] = useAddTranslationsToOpts(untransformedMap1, untransformedMap2, ...);
// instead of
const map1 = useAddTranslationsToOpts(untransformedMap1);
const map2 = useAddTranslationsToOpts(untransformedMap2);
// ...
so far what I have:
import { useTranslation } from 'next-i18next';
function useAddTranslationsToOptions<T extends OptionType[]>(...opts: T[]): [...T] {
const { t } = useTranslation();
const arr: T[] = [];
opts.forEach((map: T) => {
const transformed = map.reduce((acc: T, item) => [...acc, { text: t(item.text), value: item.value }], []);
arr.push(transformed)
});
return arr;
}
this isn't working but I think should give an idea of what I'm after here? Haven't got my head around rest spread tuple types yet but I would imagine they would solve this?
I'm not sure what you're after exactly, but maybe this helps:
function useAddTranslationsToOptions<T extends OptionType>(...opts: T[][]): T[][] {
const { t } = useTranslation();
const arr: T[][] = [];
opts.forEach((map: T[]) => {
const transformed = map.reduce<T[]>((acc, item) => [...acc, { ...item, text: t(item.text) }], []);
arr.push(transformed)
});
return arr;
}
One of the problems was that { text: t(item.text), value: item.value } is not compatible with T (although it is with OptionType).
This can be solved by using the spread operator which will add all keys and values of item to make it compatible with T:
{ ...item, text: t(item.text) }

Update field in objects array React

I have an objects array like this below:
const [categories, setCategory] = useState([
{ text: "a", active: false },
{ text: "b", active: false },
{ text: "c", active: false },
{ text: "d", active: false }
]);
and I want to update the active fields to be true. I tried something like this but it doesn't work correctly at all:
const clearFilters = () => {
setCategory(categories.map((m) => (m.active = true)));
};
const clearFilters = () => {
setCategory(categories.map((category) => ({...category, active: true})));
};
This must work. ".map" s callback function will be executed for every item of array, and every time will expect from you the new changed item. So you must return the new changed item. In my example above I used ES6 destructuring syntax, if you use ES5 it will be like this.
const clearFilters = () => {
setCategory(categories.map((category) => ({text: category.text, active: true})));
};
And yes, if you return the object in arrow function right away instead of executing function, you must put it into parentheses, otherwise it will understand it as function body, not object
Try something like below:-
const clearFilters = () => {
const clearedCategories = categories.map(m => {
m.active = true;
return m;
});
setCategory([...clearedCategories]);
};

Connecting 2 different arrays from the same external link - React hooks fetch

I am able to fetch data what url, but the thing is the url is divided into couple of arrays and I need to fetch data and connect them.
Example:
{
"array1": [
{ "data1": {"name": "Name", "phone": "Phone"}}
]
"array2" : [
{ "data2": { "color": "Color", "car": "Car" } }
]
}
Data hooks :
const userInfo = "URL";
const [userData, setUserData] = useState([]);
useEffect(() => {
getUserInfo();
}, []);
const getUserInfo = async () => {
const response = await fetch(UserInfo);
const jsonData = await response.json();
setUserData(jsonData);
};
Fetch data:
{ userData.data && userData.array1.map((array1, index) =>
<li key={"index" + index}
<h5>{array1.data1.name} </h5>
</li>
)}
I need to connect name from array1 with color from array2, but I can not find the way to do it.
Expected Output : list of data
If you can get those two arrays then you can use this to combine them:
const getUserInfo = async () => {
const response = await fetch(UserInfo);
const jsonData = await response.json();
// this assumes `jsonData` in an object with keys `array1` and `array2`
// if this is not the case, change `jsonData` below to the location of
// those two arrays
const { array1, array2 } = jsonData;
const combinedArray = array1.map(({ data1 }, i) => ({
...data1,
...array2[i].data2 // assumes there is always a corresponding index in array 2
}));
// combinedArray will look like [ { name: 'Name', phone: 'Phone', color: 'Color', car: 'Car' } ] 
setUserData(combinedArray);
};
] 

Resources