Search code examples
javascriptnode.jsreactjsapolloapollo-client

useState returning an object when adding to previous state


I have a button and onClick I'd like it to add 20 to the previous offset. However, when I do the following, i get an object for some reason:

const [ offset, setOffset ] = React.useState(20);

const { data, fetchMore } = useQuery(GET_FEED, {
 variables: {
   offset: offset,
   limit: 10
 },
 fetchPolicy: 'cache-and-network'
});

<button onClick={(prevOffset) => setOffset(prevOffset + 20)>Next</button>

Upon clicking next, the request throws a 400 and the browser says these are the variables:

variables   {…}
limit   10
offset  "[object Object]20"

If I just do:

<button onClick={() => setOffset(20)>Next</button>

It works successfully, but I'm stuck with an offset of 20.


Solution

  • You are passing in the onClick event parameter. Which is, in fact, an object...

    setState allows you to pass a function where the param is the old state. I think that is what you meant to do.

    Try below.

    const [ offset, setOffset ] = React.useState(20);
    
    const { data, fetchMore } = useQuery(GET_FEED, {
     variables: {
       offset: offset,
       limit: 10
     },
     fetchPolicy: 'cache-and-network'
    });
    
    <button onClick={() => setOffset(prevOffset => prevOffset + 20)>Next</button>