简体   繁体   中英

How to send array data to API in react native

This is the data i want to send with API but i don't know how send it because its in the form of an array, specially skills and other skills data are in the form of array

"job_type_id":"job-type-0001",
      "job_salary_type_id":"job-salary-0001",
      "employment_type_id":"employment-type-0001",
      "job_experience_id":"job-experience-0001",
      "postcodes": {
      "postcode_0": {
      "postcode_id": "postcode-0001"
      },
      "postcode_1": {
      "postcode_id": "postcode-0002"
      }
      },
      "state_id":"state-0001",
      "address":"address city",
      "job_title":"Doctor",
      "job_contact_email":"abc99@gmail.com",
      "job_contact_number":"1516555", 
      "job_description":"Test Description",
      "max_salary":"720",
      "min_salary":"710",
      "position_no":"1",
      "last_apply_date":"02-03-2022",
      "other_skills": {
      "other_skill_0": {
      "title": "ISO - @@ 1/"
      },
      "other_skill_1": {
      "title": "ISO - @@ 2/"
      }
      },
      "skills": {
      "skill_0": {
      "skill_id": "skill-0001"
      },
      "skill_1": {
      "skill_id": "skill-0002"
      },
      "skill_2": {
      "skill_id": "skill-0003"
      }
      }
     }

this is my code

 useEffect(() => {
        const fetchstateData = async () => {

            const resMr = await axios.post
                (`${urldemo}`)
            setData1(resMr.data.result);

            const responsestate = await axios.post
                (`${urldemo}`)
            setData2(responsestate.data.result);

            const responsepostal = await axios.post
                (`${urldemo}`)
            setData3(responsepostal.data.result);
            ;
            console.log("result", JSON.stringify( responsepostal, null, 2 ))
        }
        fetchstateData();
    }, []);

    const [data1, setData1] = useState([])
    const [data2, setData2] = useState([])
    const [data3, setData3] = useState([])

    const [state_id, setStateId] = useState("");
    const [postcodes, setPostcodes] = useState("");
    const [skills, setSkills] = useState("");

    const [position_no, setPosition_no] = useState("");
    const [last_apply_date, setLast_Apply_Date] = useState("");

    const handleSubmitButton = () => {
        
        if (!position_no || !last_apply_date || !skills) {
            showError("Fields Required")
            return;
        } else {

            var dataToSend = {
                job_title: job_title,
                job_description: job_description,
                max_salary: max_salary,
                min_salary: min_salary,
                experiance: experiance,
                salary: salary,
                jobMode: jobMode,
                skills: skills,
                jobType: jobType,
                state_id: state_id,
                postcodes: postcodes,
                position_no: position_no,
                last_apply_date: last_apply_date,

            };
            var formBody = [];
            for (var key in dataToSend) {
                var encodedKey = encodeURIComponent(key);
                var encodedValue = encodeURIComponent(dataToSend[key]);
                formBody.push(encodedKey + '=' + encodedValue);
            }
            formBody = formBody.join(' & ');

            let data = {
                job_title: job_title,
                job_description: job_description,
                max_salary: max_salary,
                min_salary: min_salary,
                experiance: experiance,
                salary: salary,
                skills: skills,
                jobMode: jobMode,
                jobType: jobType,
                state_id: state_id,
                postcodes: postcodes,
                position_no: position_no,
                last_apply_date: last_apply_date,

            };
            fetch(`API`, {
                method: 'POST',
                body: JSON.stringify(data),
                headers: {
                    'Content-Type': "application/json",
                    "Accept": "application/json",
                },
            })
                .then((response) => response.json())
                .then((responseJson) => {

                    console.log("response.JSON ==>", responseJson);
                    showError('Posted')

                    if (responseJson.status === 'success') {
                        console.log(
                            'Job Posted'
                        );
                        showSuccess('Successfully Posted')
                        setModalVisible(true)
                        
                    } else {
                        showSuccess(responseJson.message)
                    }
                })
                .catch((error) => {
                    console.error("Error Received ", error);
                });
        }
    }

and this is the UI CODE, i just add the picker component in which i have fetch data from API and i want to add the array data to the other API

 <Picker style={GlobalSS.picker}
                        selectedValue={postcodes}
                        mode='dropdown'
                        dropdownIconRippleColor='orange'
                        dropdownIconColor='#FF8025'
                        onValueChange={(itemValue, itemIndex) =>
                            setPostcodes(itemValue)
                        }>
                        <Picker.Item color='grey'
                            label="Select Postal Code " value="" />
                        {data3.map(item => (
                            <Picker.Item label={item.text} value={item.id} />
                        ))}
                    </Picker>

How to send array data to API in react native? you sends data like this

assume key parameter that backend recievs is arr[]

url wil be like that arr[0]=val&arr[1]=val&arr[2]=val

let arrayData= [3,4,5,6,2]
let i = 0;
let stringArrayData = ''
for (i = 0; i < arrayData.length; i++) {
     stringArrayData += `&arr[${i}]=${arrayData[i]}`
}

// stringArrayData -> you send this data to backend

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM