Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138307

useState hook not initialising with correct value: Array

$
0
0

I am passing an array 'defaults' into my panel component and then trying to set state hook 'selected option' to be equal to it. For some reason, the hook is setting an empty array instead.

component:

const Panel = ({ title, inputs, datepicker, identifiers, apiBase, isins, defaults = [], notes = "" }) => {
    const [expand, setExpand] = useState(false);
    const [date, setDate] = useState(new Date());
    const [selectedOption, setSelectedOption] = useState([...defaults]);
    const [dataError, setDataError] = useState(false);
    const [errorMsg, setErrorMsg] = useState('');
    const [errorCheckLoading, setErrorCheckLoading] = useState(false);

    const toggleExpand = () => {
        setExpand(!expand);
        console.log(defaults);
        console.log(selectedOption);
    };

Just for testing, I have a couple of console logs in my toggle expand function so I can test the data passed in against the data set.

Output from console logs:

>(48) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, 
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
>[]

So I know the data comes in ok, just that it doesn't set in the hook.

I have also tried giving the hook initial values of defaults, and [defaults].

Now drawing a blank - any ideas?


Viewing all articles
Browse latest Browse all 138307

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>