javascriptreactjsobject-destructuring

Destructure object, remove array when passing to component


I would like to pass the paging data to my component without passing the docs array.

"docs": [
   
],
"totalDocs": 18,
"offset": 0,
"limit": 10,
"totalPages": 2,
"page": 1,
"pagingCounter": 1,
"hasPrevPage": false,
"hasNextPage": true,
"prevPage": null,
"nextPage": 2

I am setting the state from my axios get:

const queryFunction = async () => {
    setLoading(true)
    axios(configFetch)
        .then(res => {
            setData(res.data); // update state with response
        })

However, I am passing all of the data to my component, how can I just pass the paging data without the docs array?

<Pager {...data} />

Solution

  • You can spread (...) out the docs, then capture 'the rest' and pass that to your <Pager />:

    const { docs, ...otherProps } = data;
    
    return <Pager {...otherProps} />
    

    Runnable demo to show how it's working:

    const obj = {
        docs: [ 1, 2, 3 ],
        foo: 'foo',
        bar: 'bar'
    };
    
    const { docs, ...otherProps } = obj;
    console.log(otherProps)