javascript – How to render Json data into an input on React Native

Hello World!

I want to render data into my contact form screen (I want the screen to be 100% configurable using call api)

Fisrt I want to render the title[Contact Us] and the subtitle[Enter your details to contact us] from the configuration Array –>Done

Second I want to render the objects on the Form Array into an inputs –>Not Yet

I’m Getting No Error

this is the code:

import React, { useState,useEffect } from 'react';
import {
  View,
  Text,
  TextInput,
  SafeAreaView,
  Keyboard,
  ScrollView,
  Alert,
} from 'react-native';

import COLORS from '../src/conts/colors';
import Button from '../src/views/components/Button';
import Input from '../src/views/components/Input';
import Loader from '../src/views/components/Loader';

const ContactForm = ({navigation}) => {
  const [inputs, setInputs] = React.useState({
    firstname: '',
    lastname: '',
    email: '',
    note: '',
  });
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);

  const validate = () => {
    Keyboard.dismiss();
    let isValid = true;

    if (!inputs.firstname) {
      handleError('Please input first name', 'firstname');
      isValid = false;
    }

    if (!inputs.lastname) {
      handleError('Please input last name', 'lastname');
      isValid = false;
    }

    if (!inputs.email) {
      handleError('Please input email', 'email');
      isValid = false;
    } else if (!inputs.email.match(/S+@S+.S+/)) {
      handleError('Please input a valid email', 'email');
      isValid = false;
    }
    if (!inputs.note) {
      handleError('Please input note', 'note');
      isValid = false;
    }

    if (isValid) {
      submitData();
    }
  };
  const submitData = ()=>{
          fetch("https://flow.simpas.ai:2021/react/contact",{
              method:"post",
              headers:{
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                  firstname: inputs.firstname,
                  lastname: inputs.lastname,
                  email: inputs.email,
                  note: inputs.note,
      })
          })
          .then(res=>res.json())
          .then(data=>{
              alert(`${data.firstname} is saved successfuly`);
              navigation.navigate("Home")
          })
          .catch(err=>{
            alert("someting went wrong")
        })

    };



  const handleOnchange = (text, input) => {
    setInputs(prevState => ({...prevState, [input]: text}));
  };
  const handleError = (error, input) => {
    setErrors(prevState => ({...prevState, [input]: error}));
  };
  const [data, getData] = useState([])
  const URL = "https://flow.simpas.ai:2021/react/contact";

  useEffect(() => {
      fetchData()
  }, [])


  const fetchData = () => {
      fetch(URL)
          .then((res) =>
              res.json())

          .then((response) => {
              console.log(response);
              getData(response);
          })
  }

  return (
    <SafeAreaView style={{ flex: 1}}>
      <Loader visible={loading} />
      <ScrollView
        contentContainerStyle={{paddingTop: 50, paddingHorizontal: 20}}>
        <Text style={{color: COLORS.black, fontSize: 40, fontWeight: 'bold',fontFamily: 'Roboto',textAlign: 'center'}}>
          {data?.title}
        </Text>
        <Text style={{color: COLORS.grey, fontSize: 18, marginVertical: 10,fontFamily: 'Roboto',textAlign: 'center'}}>
          {data?.subtitle}
        </Text>
        <View style={{ marginVertical: 20 }}>
      {data.data?.configuration[0]?.form?.map((item) => {
        return (
          <Input
            onChangeText={(text) =>
              handleOnchange(text, data?.configuration[0]?.form?.fieldname)
            }
            onFocus={() =>
              handleError(null, data?.configuration[0]?.form?.fieldname)
            }
            iconName="account-outline"
            label={data?.configuration[0]?.form?.title}
            placeholder={data?.configuration[0]?.form?.placeholder}
          />
        );
      })}

      <Button title="Contact Us" onPress={validate} />
</View>
      </ScrollView>
    </SafeAreaView>
  );
};

export default ContactForm;

This is The Json Data:

{
   "title":"Contact us",
   "subtitle":"Enter your details to contact us",
   "action":"form",
   "configuration":[
      {
         "title":"Contact us",
         "subtitle":"Enter your details to contact us",
         "type":"action",
         "actiontype":"form",
         "posturl":"https://flow.simpas.ai/interview/content/123456/businesscard/",
         "form":[
            {
               "fieldtype":"field",
               "title":"First Name",
               "fieldname":"firstname",
               "placeholder":"Enter your first name",
               "iconurl":"https://www.creativefabrica.com/wp-content/uploads/2019/02/People-Icon-by-Kanggraphic-1-580x386.jpg",
               "fieldvalue":"",
               "required":true
            },
            {
               "fieldtype":"field",
               "title":"Last Name",
               "fieldname":"latstname",
               "placeholder":"Enter your last name",
               "iconurl":"https://www.creativefabrica.com/wp-content/uploads/2019/02/People-Icon-by-Kanggraphic-1-580x386.jpg",
               "fieldvalue":"",
               "required":true
            },
            {
               "fieldtype":"email",
               "title":"Email",
               "fieldname":"email",
               "placeholder":"Enter your email",
               "iconurl":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAilBMVEX///8jHyAAAAAcFxgOBQiYl5eenZ4TCw3s7OzX1tYfGhs7ODlSUFD9/PwgHB0YExQJAAD09PR3dXaBf4AnIyQMAAXm5eYzMDHBwMDKycqIh4dAPT5bWVr39vZNSku1tLVubG2npqdqaGlFQkNaV1jGxcWvrq4tKCrR0NCQj490cnKko6O7u7vd3d1JLf0bAAAF80lEQVR4nO2ca2OyIBiGDd0oK7Bz62CnvbWt/P9/79VlBZrLAoUP9/Vt+4BciY/PA4jjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVESvtTq+28BxFS0r8JtuGQlGng2MCBluPzT7ndqEs4Y9ME52Oh17C+KbdsrhknVXl2DEuWmdu9BDU5OgZ98NPOOysQ7BJrNVMFac9DQYhnYO0TN0oS74Ri6tMUoItQAv7sY1rpO9qmCPXBqj/ndLW/BSovs1u8Y+RlX79O1dfqwfHUNeF81FkPYrOCo2FaS3kMy09Ewfg/QusqFaO9P0KaRbPf3Sx4ZeBteXUjt9nv5QVaS6CsRZ1jWcfiu1tEvfhWyjqWt6mLLbK8xVemEsL89zg4SRru6pMyBCFcCGKtG0SW4/FVEbDfqIJl5DhKg8QS0itDRq/NPWSwXes3UOUcm/JcMGI2tNyfzrNDuk0ajMMI5brnKSpMaJ5rNkrYbxbexoKVheo9sXQgzzWBWGScR509bjJ/ka0ls/+Gi1Y/oMmSs4BhPds0DleBNDDOk0nbavzZDNP8U3kG8iCx+Hwnj6HUhdjYZux9kE4iNO/ZW2rpdjL4YYb9JytBvG9YqUSJDPOiNOdyuGGNL/zWJ0G8bJ4FDMJXiNEefDFUMMn57/q9/Q6c6IFHHaanVLaWbi6CGLSwyowDD+eydezCX9GiLOeB6Il7wVOZUYJlmhFHHck0LrpdiL42bUFiqcigxzEWdRacTpLaQQI02lVGUY54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zm6Vv+5gtt+O5+aPlL/F3rbYuy7Go5y2D/Y42sUouHr+ORzNNMehSjsv5WQvs+1CKZLMM6P/typbQruaUxDojD7UYFxXN0nVE1DEnCX2YHLA/Kp/3jK8eYnHLo2MAz7e+OH4QIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABfwHS3912eO7w/wAAAAASUVORK5CYII=",
               "fieldvalue":"",
               "required":true
            },
            {
               "fieldtype":"textarea",
               "title":"Note",
               "fieldname":"note",
               "placeholder":"Enter your note",
               "iconurl":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAclBMVEX///8AAAAODg6UlJQwMDA6Ojrw8PClpaX7+/vCwsIYGBiGhoZTU1P29vbU1NTn5+fc3Nytra1+fn4rKytdXV1OTk7IyMhlZWWfn58dHR2Pj49wcHCoqKjOzs4ICAhYWFi1tbUkJCR3d3dBQUE3NzdHR0dAC+4LAAAFpElEQVR4nO2d65aiOhBGRQXxiiKKl9bBsef9X/Esp0+ThCPBxKoKfda3f3Yvk+xlSEUIVYMBAAAAAAAAAAAAAAAAAADAz2a1yXfxWIp4l29WknqXcxSC815GL63GQfwejDcpv+D+M5jfg0/27zHM/NQ5s/pl4SaoYpvxCa5noe3+MlxzCWah1WqYvsUktJdGwmK4MDvZFvlpJMMpL7Zm5wsOwZHRRb5acnTSynKVG/2P6LswLsIzzyyxk5T6EOgvRX2OTslbf40p5zxda42zLdZBR6HNENFNfoOVGkZJ27IWKT5oW3bkQw2Edi3Y1O3uSNt1Z1ePZEParpqkF9J23bnwTNNlHXDHlM16UW/+t5QRWQXDA2GrfhxYQqKaGiEX0i/Uckp5waiFhrBRX1iWmkMvDSmvmHrXfSVs1Jfr92Aod9+14ZCwUV+GMPQBhqLA0AsYigJDL2AoCgy9gKEoMPQChqLA0AsYigJDL2AoSmDDZfIunU8jghpO4uPsXY7xxN5JSMNfEQ2/+mo4IRKMIuu3GNAwJjOM+2m4PJIZHm3LTcDvc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SiHrC2ag6apdz5S2VL1HRWcW80qBqPZY78xdz563Jrk3I0Nv2iBV+YqGGvrW5LJE38FKYF/Wkl/eYwLVr1WG7LPMO4kVkSXxbTNrmoMzM0Iebilq/ILo1sY0tsw7bXfkLjqfq2yE+jt5mfreffY9Eq2cnVNhYW2CJTC3TZWV5jLhAjGqw7jw8QkoutMDpZMxSzceLfxLTQfUiCgLgKpfdgT1dr5Tn3E/cmu4u0YpyqxSG03hcXlrlaHi7yi2c7q02+i8cEfMa7Mv+YrojPxwAAAAAAAAAAAAAAAAAAAPSPfwBbfFMb/xNrvgAAAABJRU5ErkJggg==",
               "fieldvalue":"",
               "required":true
            }
         ]
      }
   ]
}

The output should look like this:

But this is what Am Getting:

enter image description here

Leave a Comment