1

The form only makes the api call (submits the form) on the 2nd click. Is it the way Im using async for the arguments? Is there something wrong with my function?

Handler Function:

const handleSubmit = async e => {
    e.preventDefault();
    searchAllImages(keyword);
  };

  const searchAllImages = async (keyword) => {
    const response = await searchImages(keyword);
    setImagelinks(response.data.message);
    const imageObjects = imagelinks.map((link, index) => {
      let newImage = {
        url: link,
        id: index,
        fav: false
      };
      return newImage;
    });
    setImages(imageObjects);
  };

Form:

<Form inline onSubmit={handleSubmit} className="form">
        <Form.Row>
          <Form.Group as={Col} md="12" controlId="keyword">
            <Form.Control
              type="text"
              name="keyword"
              value={keyword}
              onChange={e => setKeyword(e.target.value)}
              placeholder="Search a Dog"
            />
          </Form.Group>
        </Form.Row>
        <Button type="submit" className="button">
          Search
        </Button>
      </Form>
0

1 Answer 1

1

setState is asynchronous, so when you do setImagelinks(response.data.message);, ìmagelinks still not equal to response.data.message when you map on it the line below,

Try to do response.data.message.map instead like this :

const imageObjects = response.data.message.map((link, index) => {
      let newImage = {
        url: link,
        id: index,
        fav: false
      };
      return newImage;
    });
Sign up to request clarification or add additional context in comments.

1 Comment

you can mark my answer as accepted if it's ok for you, thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.