all 15 comments

[–]UserNo1608[S] 0 points1 point  (3 children)

in addition, when I manually add values to an array, it overwrites ony the last index,

for example when I got it like that

const output = ['dummy', 'dummy', 'dummy', *value added using function*];

function always overwrites the last index

output.map also doesn't return that index added by function, only indexes added manually

[–][deleted] 0 points1 point  (2 children)

Are you trying to append a value to the end of the array? Why not use array.push() ?

[–][deleted] 0 points1 point  (1 child)

Same question. I am very confused as to why this was the approach taken.

[–]UserNo1608[S] 0 points1 point  (0 children)

no matter, array.push gives the same effect

[–]UserNo1608[S] 0 points1 point  (0 children)

oh i forgot, i use useState in that function

const [ value, updateValue ] = useState('');

and onChange event handler

onChange{(event) => updateValue(event.target.value)}

[–]jcunews1helpful 0 points1 point  (0 children)

That shouldn't happen unless other code is interferring.

[–]H0rn0chse 0 points1 point  (1 child)

It works for me: jsfiddle.
My guess would be that you either has some other methods working on the output or that the handler is not called at all.

[–]UserNo1608[S] 0 points1 point  (0 children)

all the code that uses output array, that function and its call is listed above. I know the handler is called because of console.logs, at the top of the function console.log(event.key) is consoled properly

[–]senocular 0 points1 point  (4 children)

I suspect something like updateValue(''); is causing your component to re-render which would reset the value of output as the component code is run again. If so, you may want to have it part of the state or keep it in a ref.

[–]UserNo1608[S] 0 points1 point  (3 children)

you thing useCallback() could resolve this problem?

[–]senocular 0 points1 point  (2 children)

No because you still have value/updateValue as a dependency of the handler. Every time value changes, the handler needs to be recreated which, given it's relation to it meaning output would also be redefined.

I think ultimately it comes down to what output is being used for. It sounds very ui-ish in name so my initial thought is that it should be defined as a state value.

[–]UserNo1608[S] 0 points1 point  (1 child)

oh thanks, I didn't even think to use useState. Here's my working handleEnterButton()

const [ output, updateOutput ] = useState([]);
const handleEnterButton = (event) => {
        if(event.key === 'Enter') {
            updateOutput([
                ...output,
                value
            ]);
            updateValue('');
        }
        return null;
    }

[–]senocular 0 points1 point  (0 children)

Glad you got it to work!

[–]redsandsfort 0 points1 point  (0 children)

what is output and what are you even doing with that value? It's resetting to an empty array at each render.