Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kaiserkais's avatar

Update react State and then inertia get request

i want to perform inertia get request after updating state

const [filters, setfilters] = useState(['comey']);
    const addtag = (slug) => {
        setfilters([slug]);
        console.log(filters); // this give the new value as it should 
        Inertia.get('/', { tags: filters }) // but this perform a get request with initial state value , iwant it to update with the new state value
    }
0 likes
8 replies
Sinnbeck's avatar

React does not change the values in the same render. Either get a value with the filters and use in both places or use useEffect()

kaiserkais's avatar

@Sinnbeck sir can you explain more how can i handle it. this my second project with react.

Sinnbeck's avatar

@kaiserkais have used useEffect() before?

And here an example of using the same value as in setState

const addtag = (slug) => {
        setfilters([slug]);
        
        Inertia.get('/', { tags: [slug]}) 
kaiserkais's avatar

@Sinnbeck when i use useEffect it keeps firing even if the filters not changed, the method you right before dont solve my problem because im not going to use other filters as well, this is why i used the state

// the filters will be 
[{tags: ['come', 'tag2'], cats:['cat1', 'cat2']}] //and more 
Sinnbeck's avatar

@kaiserkais show how you set up the useEffect then. And please use the actual code if what you are showing is not exactt :)

Sinnbeck's avatar

@kaiserkais normally useEffect keeps refiring if what you are checking for is being changed by the useEffect.

kaiserkais's avatar

@Sinnbeck let me explain what i want to do because my code is not completed yet i want to untherstand how filtering worl along with change of state first i have buttons

<button onclick="() => addTag('tag1')">taga1</button>
<button onclick="() => addTag('tag2')">taga2</button>

and i have a state :

const [filters, setfilters] = useState([]);

when i click on the button it will push the tag1 to the filter state and the result will be

 const addtag = (slug) => {
        setfilters(); // pushing the value te get this result 

when the state updated i shoud be like

	{
		ingredient: ['tag1', 'tag2']
	}

then im going to send inertia request every time the state change

        Inertia.get('/', filters) // but this perform a get request with initial state value , iwant it to update with the new state value
    }

the problem now the inertia request always send empty even if the state updated in devtool if i use useEffect like you mention it keep firing even if the filters not updated .

kaiserkais's avatar
kaiserkais
OP
Best Answer
Level 2

I Found The Solution that i didnt use { preserveState: true } this is why it always the state refresh to the initial state

Please or to participate in this conversation.