axrising
@axrising

Как генерировать id для нового поста в Formik?

Как при добавлении нового поста в redux, диспачить вместе с данными формы новый id для поста?
Какие могут быть решения, заранее спасибо

export type PostType = {
  id: number
  postMessage: string
  file: any | null
}

   const PostForm: React.FC<PostForm> = ({ addNewPost }) => {
  const classes = useStyles()
  return (
    <Formik
      initialValues={{
        postMessage: '',
        file: null,
      }}
      validationSchema={Yup.object({
        postMessage: Yup.string().max(15, 'Must be 15 characters or less').required('Required'),
      })}
      onSubmit={(values: PostType, onSubmitProps) => {
        setTimeout(() => {
          addNewPost(values)
          onSubmitProps.resetForm()
        }, 0)
      }}
    >
      {({ isSubmitting, touched, errors, handleBlur, handleChange, values, setFieldValue }) => (
        <Form>
          <Paper className={classes.myPostWrap}>
            <Grid container alignItems='center'>
              <div className={classes.inputWrap}>
                <TextField
                  margin={'dense'}
                  variant='outlined'
                  name='postMessage'
                  placeholder='New Post'
                  value={values.postMessage}
                  onBlur={handleBlur}
                  onChange={handleChange}
                  error={touched.postMessage && Boolean(errors.postMessage)}
                  helperText={touched.postMessage && errors.postMessage}
                  className={classes.inputUi}
                />
                <input
                  accept='image/*'
                  style={{ display: 'none' }}
                  id='icon-button-file'
                  type='file'
                  name='file'
                  onChange={(e: any) => {
                    setFieldValue('file', e.currentTarget.files[0])
                  }}
                />
                <label htmlFor='icon-button-file'>
                  <IconButton className={classes.uploadBtn} size={'small'} aria-label='upload picture' component='span'>
                    <PhotoCamera />
                  </IconButton>
                </label>
                {values.file ? (
                  <Typography className={classes.fileName} variant={'subtitle2'}>
                    {values.file.name}
                  </Typography>
                ) : null}
              </div>

              <Button type='submit' variant='contained' color='primary' disabled={isSubmitting}>
                Add post
              </Button>
            </Grid>
          </Paper>
        </Form>
      )}
    </Formik>
  )
}


  const addPost = (post: PostType) => {
    dispatch(actions.addPost(post))
  }


  switch (action.type) {
    case 'SN/PROFILE/ADD_POST': {
      let newPost = {
        id: action.post.id,
        postMessage: action.post.postMessage,
        file: action.post.file,
      }
      return {
        ...state,
        posts: [...state.posts, newPost],
      }
    }
  • Вопрос задан
  • 58 просмотров
Пригласить эксперта
Ответы на вопрос 1
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы