update State inside Map Function immediately React hooks - reactjs

I tried with the below code but it is executing on the second attempt, I want to execute Alert on the Dropdown function, I am not rendering returnCount just using it to display an alert,
anyone knows the answer plz answer this, don't send any link, nothing is working out instead please write the answer
const [arrayList, setArrayList] = useState([
{ Id: 1, Name:'A', ItemDeliveryStatus:4 },
{ Id: 2, Name:'B', ItemDeliveryStatus:4 },
{ Id: 3, Name:'C', ItemDeliveryStatus:4 },
{ Id: 4, Name:'D', ItemDeliveryStatus:4 },
])
const [returnCount ,setReturnCount ]=useState(0)
//function on the picker, want to update returnCount immediately so that I can use it for below alert
function displayalertBox(){
arrayList.map(items =>
{
if(items.ItemDeliveryStatus=='4')
{
setReturnCount(prev=> prev+1)
}
})
if(returnCount==4)
{
alert('alert as returncount is equal to 4')
}
}

You need to do the desired functionality inside of an useEffect when using react hooks.
const [arrayList, setArrayList] = useState([{
Id: 1,
Name: 'A',
ItemDeliveryStatus: 4
},
{
Id: 2,
Name: 'B',
ItemDeliveryStatus: 4
},
{
Id: 3,
Name: 'C',
ItemDeliveryStatus: 4
},
{
Id: 4,
Name: 'D',
ItemDeliveryStatus: 4
},
])
const [returnCount, setReturnCount] = useState(0)
function displayalertBox() {
arrayList.map(items => {
if (items.ItemDeliveryStatus == '4') {
setReturnCount(prev => prev + 1)
}
})
}
// You cantry this too if needed.
function displayalertBox1() {
arrayList.map(items => {
if (items.ItemDeliveryStatus == '4') {
let count
setReturnCount(prev => {
count = prev + 1;
//since state update is guaranteed, you can try this too.
if (count === 4) {
alert('alert as returncount is equal to 4')
}
return count
})
}
})
}
useEffect(() => {
if (returnCount == 4) {
alert('alert as returncount is equal to 4')
}
}, [returnCount]);

Related

find a specifik obejct with arrays and print it out, react

I want to use find when clicking a button, I want to find an obejct (working in react)
let numbers = [
{ id: 0, namn: one, img: "../number/one" },
{ id: 1, namn: two, img: "../number/two" },
{ id: 2, namn: three, img: "../number/three" },
];
const [selected, setSelected] = useState({
id: 0,
name: "one",
img: "../number/one",
});
const count = useRef(0);
function next() {
if (count.current === 2) {
count.current = 0;
let found = numbers.find((number) => number.id === count.current);
} else {
count.current = count.current + 1;
let foundtwo = numbers.find((number) => number.id === count.current);
}
return (
<>
<img>{selected.img}</img>
namn: {selected.name}
</>
);
}
I can find it but I want to put it in a useState.
or somehow get it to show. how can I get found, and found two out in the return
the awswer was to put a
if( found === undefined){
console.log("error")
}else{
setSelected(found)
}

Select or deselect item in array and increase or decrease its value react native

Basically i want to select an emoji from an array which contains objects (id, name, count) and if i select an item on the array i want to increase its value and if i deselct it i want to decrease its value
for now i've done this which basically increase the value of an item in the array, please help me, thanks.
this is the array
const [emojisArr, setEmojisArr] = React.useState([
{
name: 'like',
emoji: '👍',
count: 11,
},
{
name: 'heart',
emoji: '❤️',
count: 21,
},
{
name: 'joy',
emoji: '😂',
count: 31,
},
{
name: 'fire',
emoji: '🔥',
count: 34,
},
{
name: 'star',
emoji: '💯',
count: 5,
},
]);
and this is the function when i click on the button
const likePost = item => {
const index = emojisArr.findIndex(emoji => emoji.name === item);
emojisArr[index].count += 1;
setEmojisArr(old => [...old]);
}
Set this code see below. you can pass action (selected/deselected) as string. so, it can increment/decrement count on the behalf of action.
const post = (item, action) => {
const newState = emojisArr.map((emoji) => {
if (emoji.name === item) {
return {
...emoji,
count: action === "selected" ? emoji.count + 1 : emoji.count - 1
};
}
return emoji;
});
setEmojisArr(newState);
};

need to implement Undo function using react hooks

need to implement undo function in a state array data. i remove the data by id using filter method but i need to restore the data after click on undo button. how to implement in React Hooks?
const [dataSource, setDatasource] = useState([
{
id: 1,
name: 'john',
gender: 'm'
},
{
id: 2,
name: 'mary',
gender: 'f'
},
{
id: 3,
name: 'loki',
gender: 'M'
},
{
id: 4,
name: 'Thor',
gender: 'M'
},
]);
You will have to keep track of all the actions that the user performs, and calculate the end result from that. When a user clicks "undo", you can just remove the latest action.
const actions = [
{
operation: "create",
name: "Some name",
index: 1
},
{
operation: "delete",
index: 1
}
];
const state = (() => {
let appliedState = [];
for (const action of actions) {
if (action.operation === "create") {
appliedState .push(action.name);
} else if (action.operation === "delete") {
appliedState = appliedState .filter(currentState => currentState.index !== action.index);
}
}
return appliedState ;
})();
You can see a working react example here.

How to update Nested state in ReactJs

how to update nested state in reactjs, such as I have an Array of an object of course
state = {
courses: [
{ id: 1, coursename: "CSS3", like: 25, dislike: 0 },
{ id: 2, coursename: "Javascript", like: 45, dislike: 0 },
{ id: 3, coursename: "ReactJS", like: 294, dislike: 0 }
]
};
now i want to update like on the particular course only on onClick , after updating it should be 26 . and again if i click it should decremented by 1.
You can find the code in codesandbox
In your handleLike method, you can map the courses and update the like field of the given course like this:
handleLike = id => {
console.log("id", id);
const updatedCourses = this.state.courses.map(c => {
if (c.id === id) {
return {
...c,
like: c.like + 1
};
} else {
return c;
}
});
this.setState({
courses: updatedCourses
});
};

Update state that depends on other calculated state in React-Hooks

I want to update a state (data) that depends on other calculated state (server)
setServer(prevTweets =>
[...json, ...prevTweets].filter(
(e, i, arr) => i === arr.findIndex(t => t.tweetId === e.tweetId)
)
)
The data above will be used to set the state below (data) :
let totalPositive = 0;
let totalNegative = 0;
let totalNeutral = 0;
server.forEach(tweet => {
if(tweet.sentiment >0) totalPositive++;
if(tweet.sentiment < 0) totalNegative++;
if(tweet.sentiment ===0) totalNeutral++;
})
setData([
{ name: 'Positive', value: totalPositive },
{ name: 'Negative', value: totalNegative },
{ name: 'Neutral', value: totalNeutral },
])
Since it's asynchronous, the setData operation is always late. I know that I can use useEffect but apparently it will make an infinite loop and it's not right to use it in this case.
If you set the new data before you set the server you'd skip one render:
//still defaults to server so if you do't pass anything it;s still the same
const setNewData = (newServer = server) => {
const [
totalPositive,
totalNegative,
totalNeutral,
] = newServer.reduce(
([pos, neg, neu], { sentiment }) =>
sentiment > 0
? [pos + 1, neg, neu]
: sentiment < 0
? [pos, neg + 1, neu]
: [pos, neg, neu + 1],
[0, 0, 0]
);
setData([
{ name: 'Positive', value: totalPositive },
{ name: 'Negative', value: totalNegative },
{ name: 'Neutral', value: totalNeutral },
]);
};
setServer(prevTweets => {
const newServer = uniqueByTweetId([
...json,
...prevTweets,
]);
setNewData(newServer);
return newServer;
});
Unrelated to the question but could be important is that the way you get unique values could be improved. You could get unique values in one pass without having to call find index many times:
const uniqueBy = getter => arr => {
const items = new Map();
return arr.filter(item => {
const key = getter(item);
const ret = items.get(key);
items.set(key,true);
return !ret;
});
};
const data = [
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 },
{ id: 5 },
{ id: 1 },
{ id: 7 },
{ id: 1 },
{ id: 7 },
{ id: 8 },
{ id: 1 },
];
const uniqueById = uniqueBy(i => i.id);
console.log(uniqueById(data));

Resources