Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
89 views
in Technique[技术] by (71.8m points)

javascript - react form input values are not showing correctly

i am working on a project and creating a form to create tours. everything is working fine just the issue is form input values are exchanging

for ex -

actual output- { tourName: 'pune darshan', location: '999', price: 'pune' } expected output :- { tourName: 'pune darshan', location: 'pune', price: '999' }

i dont know where i am going wrong i am stuck here since 6 hrs

here is what i have tried

form component


import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { createTour } from "../../store/slices/tourSlice";
import "./createListing.scss";

const CreateListing = () => {
  const [tour, setTour] = useState({
    tourName: "",
    price: "",
    location: "",
  });
  const dispatch = useDispatch();
  const handleInput = (event) => {
    setTour((tour) => ({
      ...tour,
      [event.target.name]: event.target.value,
    }));
  };
  const handleSubmit = (event) => {
    event.preventDefault();
    dispatch(createTour(tour.tourName, tour.price, tour.location));
  };

  return (
    <div>
      <div className='form-controller'>
        <form action='' method='post' onSubmit={handleSubmit}>
          <div className='form-group'>
            <input
              type='text'
              className='form-control'
              name='tourName'
              placeholder='Enter Tour Name'
              onChange={handleInput}
              required
            />
          </div>
          <div className='form-group'>
            <input
              type='text'
              className='form-control'
              name='location'
              placeholder='Enter Tour Location'
              onChange={handleInput}
              required
            />
          </div>

          <div className='form-group'>
            <input
              type='number'
              className='form-control'
              name='price'
              placeholder='Enter Tour Cost'
              onChange={handleInput}
              required
            />
          </div>
          <div className='text-center'>
            <button type='submit theme-btn'>Create Tour</button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default CreateListing;

here is the redux toolkit file

import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";
import { history } from "./../../helpers/history";

export const initialState = {
  tourName: "",
  location: "",
  price: "",
  error: "",
  loading: false,
};

const tourSlice = createSlice({
  name: "tour",
  initialState,
  reducers: {
    tourCreateRequest: (State, action) => {
      return {
        loading: true,
      };
    },
    tourCreateSuccess: (state, action) => {
      return { loading: false, tourInfo: action.payload };
    },
    tourCreateFail: (state, action) => {
      return {
        loading: false,
        error: action.payload,
      };
    },
  },
});

const {
  tourCreateFail,
  tourCreateRequest,
  tourCreateSuccess,
} = tourSlice.actions;

export default tourSlice.reducer;

export const createTour = (tourName, location, price) => async (dispatch) => {
  try {
    dispatch(tourCreateRequest);

    const tourData = {
      tourName,
      location,
      price,
    };

    const res = await axios.post(
      "http://localhost:3000/api/v1/tours",
      tourData
    );

    if (res) {
      dispatch(tourCreateSuccess);
      // history.push("/dashboard");
    } else {
      dispatch(
        tourCreateFail(
          error.response && error.response.data.message
            ? error.response.data.message
            : error.message
        )
      );
      console.log("error");
    }
  } catch (error) {
    dispatch(
      tourCreateFail(
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message
      )
    );
  }
};

here is the model file

const mongoose = require("mongoose");

const tourSchema = mongoose.Schema(
  {
    tourName: { type: String },
    rating: { type: String, default: 4.5 },
    location: { type: String },
    price: { type: String, default: 999 },
  },
  { timestamps: {} }
);

const Tour = mongoose.model("Tour", tourSchema);
module.exports = Tour;

here is controller code

const createTours = async (req, res, next) => {
  const { tourName, price, location } = req.body;
  console.log(req.body);
  try {
    const newTour = new Tour({
      tourName,
      price,
      location,
    });
    newTour.save();
    res.status(200).json({
      status: "success",
      newTour,
    });
  } catch (error) {
    res.status(404).json({
      status: "failed",
      error: error,
    });
  }
};
question from:https://stackoverflow.com/questions/65860148/react-form-input-values-are-not-showing-correctly

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You pass the parameters in the createTour function in the wrong order. You should update the dispatch line:

dispatch(createTour(tour.tourName, tour.location, tour.price));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...