October 22, 2024
Chicago 12, Melborne City, USA
javascript

How to integrate LocationIQAutocomplete data into formData state in React?


I’m working on a React component to create a trip planner. I’m using the useState hook to manage form data with an object called formData, and everything works fine with regular inputs and selections. However, I’m having trouble integrating data from a custom LocationIQAutocomplete component into the same formData state.

Here’s a simplified version of my index.jsx:


import React, { useState, useEffect } from "react";
import LocationIQAutocomplete from "@/components/LocationIQAutocomplete/LocationIQAutocomplete.jsx";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";

function CreateTrip() {
  const [formData, setFormData] = useState({});
  
  const handleInputChange = (name, value) => {
    setFormData({
      ...formData,
      [name]: value,
    });
  };

  useEffect(() => {
    console.log(formData);
  }, [formData]);

  return (
    <div>
      <h2>Tell us your travel preferences</h2>

      {/* Other form inputs */}
      <div>
        <h3>What is your destination choice?</h3>
        <LocationIQAutocomplete />
      </div>

      <div>
        <h3>How many days are you planning?</h3>
        <Input
          type="number"
          onChange={(e) => handleInputChange("noOfDays", e.target.value)}
        />
      </div>

      {/* More inputs... */}
      
      <Button>Generate Trip</Button>
    </div>
  );
}

export default CreateTrip;

Issue:
I can easily update the formData using regular inputs like the one for noOfDays with handleInputChange. However, I’m struggling to update the formData with the selected location data from the LocationIQAutocomplete component.

I passed the data from the autocomplete component as a prop, but I’m unsure how to integrate the selected value from LocationIQAutocomplete into my formData.

How can I capture the selected location from LocationIQAutocomplete and update my formData state in React?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video