concatenating 2 arrays unexpected result [duplicate] - javascript

This question already has answers here:
React hooks stale state
(1 answer)
State not updating when using React state hook within setInterval
(14 answers)
Wrong React hooks behaviour with event listener
(9 answers)
Closed 1 year ago.
I am trying to update my array state with a list of records I am getting from an API, I am trying it as follows:
const [record, setRecord] = useState([])
const addRecords= async ()=>{
const apiResult = await apicall()
setRecord(record.length ? [...apiResult, ...record] : apiResult)
}
however every time the api is called is overwritting my 'record' with the last items added from the api instead of putting them together.
I also tried using .concat() with same result
const addRecords=async()=>{
const apiResult = await apicall()
setRecord(record.concat(apiResult ? apiResult:[])
}
there is sth here I am not managing to understand, hope someone can clarify what can it be.

I think you want to use a function in your setter to get your previous value (I dont understand enough to give you the reason why, but I think it has something to do with your record being a frame or two out of date)
const addRecords=async()=>{
const apiResult = await apicall()
//prevRecord is more recent than record (I think)
setRecord(prevRecord=>prevRecord.concat(apiResult || [])
}

Related

How to get state name from function argument when using setState in React [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 11 days ago.
I have the following state in my React Component:
class App extends Component {
constructor(props) {
super(props);
this.state = {
temperatureBedroom: 22.0,
temperatureLivingRoom: 23.0,
...
Now, I would like to update the state with the this.setState function.
The most straightforward way to do it is to just use the following code:
increaseTemp = () => {
let increment = 0.5;
this.setState({
temperatureBedroom: this.state.temperatureBedroom + increment
});
...
However, the problem is that with this approach I have to define a new (handler) function for each of the states (variables), i.e., as in my example -- rooms, for which I'd like to set a new value (temperature).
I was wondering if there is a more efficient way in React to address this issue.
The desired outcome would be to have something like that for the Buttons control:
<Button
variant="outline-secondary"
onClick={() =>
this.increaseTemp("temperatureBedroom")
}
>
+
</Button>
and I would like to use this argument like that:
increaseTemp = (roomName) => {
let increment = 0.5;
this.setState({
roomName: this.state.roomName + increment
});
...
The documentation doesn't mention a simple way to do it. It shows an example of writing separate handler functions for each state variable, see e.g.: https://beta.reactjs.org/learn/updating-objects-in-state
I have found similar questions, but some other aspects of the setState are discussed there, none of them addresses specifically the issue I would like to resolve:
How to setState from function parameter in React
Using function name as parameter of setState method?
Maybe I could try using a function as a setState parameter, but I am not sure if it helps with my problem: https://medium.com/#wisecobbler/using-a-function-in-setstate-instead-of-an-object-1f5cfd6e55d1
I would appreciated any suggestions how to avoid writing redundant handler functions.

Why console.log() is logging 4 times and it's different? [duplicate]

This question already has answers here:
My React Component is rendering twice because of Strict Mode
(6 answers)
Closed 2 months ago.
export default function course() {
const router = useRouter()
slu= router.asPath.split("/")[2]
console.log(slu)
return (<design goes here>);
}
So the problem here is that when I use this method it gives me this output
What I want is the value 1731547675 but instead of that it's giving me [slug]
What's wrong that I am doing here
It Prints multiple times because the ui is refreshed everytime You set a state
Wrap Your Console.log into a useEffect block
const [slu, setslu] = useState(0);
useEffect(()=>
setslu(router.asPath.split("/")[2])
}
Hopefully this helps. Note: Use const instead of let in creating a state

Difference between these Two syntaxes in React [duplicate]

This question already has answers here:
What's the difference between passing a value and passing a callback in a React setState hook function?
(2 answers)
Closed 4 months ago.
I'm not an expert in React Js and want to know the difference between these two syntaxes in the ES6 syntax.
const items = array.map(thing => <p key={thing}>{thing}</p>)
function addItem(){
setArray(previtems => { return [...previtems, `Thing ${array.length + 1}`]});
}
and
const items = array.map(thing => <p key={thing}>{thing}</p>)
function addItem(){
setArray([...items, `Thing ${array.length + 1}`]);
}
The first one is functional setState. It gives guarantee that the value of prevItems will be the most updated one. This pattern is to be used whenever next state depends on the previous state.

the use of ... element in jsx file [duplicate]

This question already has answers here:
javascript es6 array feature [...data, 0] "spread operator"
(2 answers)
Closed 5 months ago.
I am a beginner at React learning it from an online tutorial.
there is an element used in one of the courses which is ... and can be seen in the following code
handleIncrement = (productId)=>{
const newProducts=[...this.state.products]
const index= newProducts.findIndex(p=> p.id === productId)
newProducts[index].count +=1 ;
this.setState({products : newProducts});
}
its usage seems to be creating an array from products and passing it to the newProducts which is an array now. could you please explain what exactly do ... and when we need it to use?
It's called the spread syntax.
In react, you're not supposed to mutate the state directly. So, if you have an array you want to edit, you will first create a copy of the array with the spread syntax, edit the new array, and finally set the state to the edited copy of the array.
Creating a copy with newProducts = this.state.products is not sufficient in this case as both the variables are pointing to the same object in memory and changing newProducts is the same as changing `this.state.products.

Let vs Var with AsyncStorage Strange Exception [duplicate]

This question already has answers here:
Cannot use let to define a variable with the same name of function's parameter
(2 answers)
Javascript ES6 'let' and 'var' - unexpected behavior inside function with argument name matching redeclared variable
(1 answer)
Closed 3 years ago.
To replicate the below, run this code on React Native 0.59.8
I have a function that looks like the below:
import AsyncStorage from 'react-native';
const saveToStorage = async (value) => {
await AsyncStorage.setItem('#store.key', value);
let value = await AsyncStorage.getItem('#store.key');
// Exception is thrown on ios because value is seen as null
}
But if I changed let to var the request is processed successfully.
const saveToStorage = async (value) => {
await AsyncStorage.setItem('#store.key', value);
var value = await AsyncStorage.getItem('#store.key');
// No exception is thrown on ios
}
Does anyone have an idea what is going on?
I would comment this if I could but I think there's a couple things that you could change. Don't name that variable value because you are passing a parameter called value into your async function, so value will already be defined. Also I think you are missing an await in your AsyncStorage.getItem('#store.key')

Categories