首页 > 解决方案 > how can I know I have access to this state in this function?

问题描述

for my edit profile page I need to call 2 APIs for change profile picture. I used fetch(). the way APIs works is at first I send user id, and expect a response that is a number for upload id. and then I send that id to the next API as a name for the image. also I store my base64 image to a sate and the second API doesn't work properly because I assume that I can not access to the image state in this function. I cant console log the image inside the function it gave me this:

PayloadTooLargeError: request entity too large

here is my implementation for this:

  const [image, setImage] = useState(null);
  const [imageUploading, setImageUploading] = useState(false);
  const [uploadId, setUploadId] = useState('');
  const userData = useSelector(state => state.user.userData)

  const logOutHandler = async () => {
    try {
      await AsyncStorage.removeItem('loginData').then(() => {
        props.navigation.reset({
          index: 0,
          routes: [{ name: 'Login' }]
        })
      })
    } catch (e) {
      console.log(e)
    }
    console.log('Done.')
  }

  const allowAccess = async () => {
    if (Platform.OS !== 'web') {
      const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (status !== 'granted') {
        alert('Sorry, we need camera roll permissions to make this work!');
      } else {
        pickImage()
      }
    }
  }

  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
      base64: true
    });

    if (!result.cancelled) {
      setImage(result.base64);
      uploadImage()
    }
  };

  const uploadImage = () => {
    
    fetch('URL',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            "id": userData.id
          })
      })
      .then(response => response.json()) // pass the data as promise to next then block
      .then(data => {
        setUploadId(data)
      })
      .catch((err) => console.log(err))

      
        fetch('URL2',
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
              "fileName": uploadId,
              "fileBase64String": image,
              "folderName": 'User',
              "fileExtension": '.jpg'
            })
        })
        .then(response => response.json()) // pass the data as promise to next then block
        .then(data => {
          console.log('here....' ,data)
        })
        .catch((err) => console.log(err))
  }

标签: javascriptreactjsreact-nativefetch

解决方案


您可以按照以下两个步骤进行:-

  1. 尝试从 fetch api 中删除标头

  2. 代替标题中内容类型的 application/json 值添加 application/x-www-form-urlencoded

    headers: {
                 'Content-Type': 'application/x-www-form-urlencoded'
             }
    

推荐阅读