Bessem
Bessem

Reputation: 55

how can I get the current value when I map an array in react

I want to get the current value and save it in the state but I get too many renders... I'm mapping through data then I want to get render the UI based on that but also get the current data in the display so I can use it in another function in the same component.

{DATA.map(({ title, fields }) => {
              setCurrentFields(fields.map((field) => field.name));
              //this above cause the error but I want find a way to save that part of the data somewhere
              return (
                <Step label={title} key={title}>
                  <Box
                    textAlign="center"
                    p="3"
                    overflowY="auto"
                    height="100%"
                  >
                    {fields.map(
                      ({
                        name,
                        validation = { required: true },
                        placeholder,
                        type,
                      }) => {
                        console.log(fields.length);
                        return (
                          <FormField key={name} errors={errors} name={name}>
                            <Input
                              id={name}
                              name={name}
                              placeholder={placeholder}
                              type={type}
                              {...register(name, validation)}
                            />
                          </FormField>
                        );
                      }
                    )}
                  </Box>
                </Step>

Upvotes: 0

Views: 375

Answers (1)

Rodrigo Echeconea
Rodrigo Echeconea

Reputation: 136

You can't do state management inside a render because state update will trigger a rerender every time you update. What you should do is iterate this DATA array somewhere outside the render and update states there. Useeffect is probably what you are looking for.

Also, take into consideration that you are rewriting the state for each element on the data array, so in the end you will only have the state of the final element saved in you currentValues state.

Upvotes: 1

Related Questions