Home > database >  reverse method is called every time i type in my input box (onChange)
reverse method is called every time i type in my input box (onChange)

Time:10-30

i have a variable that i'm using to store the reversed array returned from an api, but everytime i type in the input box to create a new activity, the array reverses. My guess is that it's something with the state and the onChange function?

(i want the array to be reversed so the most recent post is shown at the top and i don't have to scroll past tons of posts to see if mine was created, by default it's the newest post shown last)

this is the component so far: `

const Activities = ({ token, activities, fetchActivities }) => {
    const [createName, setName] = useState('');
    const [createDesc, setDesc] = useState('');

    const reverseActivities = activities.reverse();

    async function addActivity() {
        try {
            const newActivity = {
                token: token,
                name: createName,
                description: createDesc
            }

            await createNewActivity(token, newActivity);
            fetchActivities();

            alert('success!')
        }
        catch (err) {
            console.error('addActivity-activities.js FAILED:', err);
        }

    }

    return (
        <div>
            <h1>Activities</h1>
            <form>
                <h2>Create a new activity</h2>
                <input
                    type='text'
                    placeholder='Name'
                    onChange={(e) => {
                        e.preventDefault();
                        setName(e.target.value)
                    }} />
                <input
                    type='text'
                    placeholder='Describe activity'
                    onChange={(e) => {
                        e.preventDefault();
                        setDesc(e.target.value)
                    }} />
                <button
                    type='submit'
                    onClick={(e) => {
                        e.preventDefault();
                        addActivity();
                    }}
                >Create Activity</button>
            </form>

            {
                reverseActivities.map((activity) => {
                    const { name, id, description } = activity

                    return (
                        <div key={id}>
                            <h3>{name}</h3>
                            <p>description: {description}</p>
                        </div>
                    )
                })
            }

        </div>



    )
}

` i've tried to move the variable declaration to the top of the component as well as doing activties.reverse().map(....) instead of declaring the variable and then mapping over the array. Neither really made a difference.

CodePudding user response:

Every time state changes, react will re-render your component. Because you update state each time a character changes activities.reverse(); will keep getting called. This could be solved with a useMemo but in your case I do not think that would solve the problem.

I think your confusion stems from the fact that reverse modifies the array it is called on and returns a reference to the original array.

> const array = [1,2,3,4,5]
undefined
> const reversed = array.reverse()
undefined
> reversed
[ 5, 4, 3, 2, 1 ]
> array
[ 5, 4, 3, 2, 1 ]
> reversed == array
true

You could create a new array with [...array] then reverse that one.

> const array  = [1,2,3,4,5]
undefined
> const reversed = [...array].reverse()
undefined
> reversed
[ 5, 4, 3, 2, 1 ]
> array
[ 1, 2, 3, 4, 5 ]
  • Related