React: The image that the user selected is different from the result coming from res.data

Viewed 21

I'm creating a component that will create a post with descriptions and images, using react js and multer. The problem is the some of the images that I selected have been remove and replacing twice by the same images. I already check the code by using console log the result is fine but after the axios post request the list of images changes. Can you help me why this thing happen?

createPost.js
const UserPost = ({ userData }) => {
  const { username: usernameProps } = userData;

  const [postInfo, setPostInfo] = useState({
    username: '',
    description: '',
    postImageCollection: '',
  });

  useEffect(() => {
    setPostInfo({ username: usernameProps });
  }, [usernameProps]);

  const dispatch = useDispatch();
  const classes = UseStyles();

  const handlePost = async (e) => {
    e.preventDefault();

    const fData = new FormData();
    for (let i = 0; i < postImageCollection.length; i++) {
      fData.append('postImageCollection', postImageCollection[i]);
      **console.log('postImageCollection', postImageCollection[i]); <-- here the list of images is correct**
    }

    try {
      await axios({
        method: 'POST',
        url: 'http://localhost:5000/user/posts',
        data: fData,
        headers: {
          'content-type': 'multipart/form-data',
        },
      }).then((res) => {
        **console.log(res.data); <-- this is where the list of images changes**
        // setPostInfo((prevImgCollection) => ({
        //   ...prevImgCollection,
        //   postImageCollection: res.data,
        // }));
      });
    } catch (error) {
      console.log(error.response);
    }
    dispatch(createPost(postInfo));
  };

  const handleChangeImageCollection = (e) => {
    const newArray = [...postImageCollection];
    for (let i = 0; i < e.target.files.length; i++) {
      newArray.push(e.target.files[i]);
    }

    setPostImageCollection(newArray);
    if (newArray.length > 5) {
      setCurrentImageHide('+' + (newArray.length - imagePerPost));
    }
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setPostInfo((prev) => ({ ...prev, [name]: value }));
  };

  const indexOfLastImage = currentImagePost * imagePerPost;
  const indexOfFirstImg = indexOfLastImage - imagePerPost;
  const currentImage = postImageCollection.slice(
    indexOfFirstImg,
    indexOfLastImage
  );

  return (
    <Container
      component='div'
      className={classes.userPostContainer}
      style={{ padding: '0', margin: '0' }}
    >
      <Card className={classes.userPostCard} style={{ boxShadow: 'none' }}>
        <CardContent style={{ padding: '0 0 1.5em 0' }}>
          <form noValidate onSubmit={handlePost}>
            <Grid container>
              <Grid item xs={12}>
                <TextField
                  variant='outlined'
                  id='description'
                  name='description'
                  type='text'
                  value={postInfo.description}
                  onChange={handleChange}
                  placeholder={`What's on your mind, ${
                    userData && userData.username
                  }`}
                  fullWidth
                  InputLabelProps={{
                    classes: {
                      root: classes.label,
                      focused: classes.focused,
                    },
                  }}
                  InputProps={{
                    className: classes.textfieldBg,
                    classes: {
                      root: classes.cssOutlinedInputBg,
                      focused: classes.cssFocused,
                      notchedOutline: classes.NonotchedOutline,
                    },
                  }}
                />
              </Grid>
              <Grid
                xs={12}
                container
                className={classes.postPhotoContainer}
                style={{ padding: '0' }}
              >
                <Grid xs={12}>
                  <ImageList
                    postImageCollection={currentImage}
                    currentImageHide={currentImageHide}
                  />
                </Grid>
                <Grid xs={10}>
                  <input
                    accept='image/*'
                    id='postImageCollection-file-button'
                    type='file'
                    name='postImageCollection'
                    onChange={handleChangeImageCollection}
                    multiple
                  />
                  <label htmlFor='postImageCollection-file-button'>
                    <ImageIcon />
                    Add Photo
                  </label>
                </Grid>
                <Grid
                  xs={2}
                  style={{
                    padding: '0',
                    margin: '0',
                    display: 'flex',
                    justifyContent: 'center',
                  }}
                >
                  <Button
                    type='submit'
                    variant='contained'
                    startIcon={<SendIcon />}
                  >
                    Post
                  </Button>
                </Grid>
              </Grid>
            </Grid>
          </form>
        </CardContent>
      </Card>
    </Container>
  );
};

The correct output

0: "http://localhost:5000/public/images/post/postImageCollection-1616065863529.jpg" 1: "http://localhost:5000/public/images/post/postImageCollection-1616065863529.jpg" 2: "http://localhost:5000/public/images/post/postImageCollection-1616065863530.jpg"

The incorrect output

0: "http://localhost:5000/public/images/post/postImageCollection-1616065863529.jpg" 1: "http://localhost:5000/public/images/post/postImageCollection-1616065863529.jpg" 2: "http://localhost:5000/public/images/post/postImageCollection-1616065863530.jpg"

0 Answers
Related