setState on updating values on page - reactjs

For the code below when the data is sent from the other page with the state I am trying to set default values and have the text be reflected one the page. The data is being successfully sent to the page but the constants aren't being updated with the useState hook. I checked several sources and still couldn't find a solution that helped this specific bug
Picture of the page
import React, {useEffect} from 'react';
import {Col, Container, Form, Row} from "react-bootstrap";
import Header from "./Header";
import Footer from "./Footer";
import {useState} from "react";
import {useLocation} from "react-router-dom";
import {render} from "react-dom";
const Bookings = () => {
/*Constants for ticket pricing*/
const [kingston_ticket_cost] = useState(180);
const [portland_ticket_cost] = useState(200);
const [negril_ticket_cost] = useState(280);
const [ochorios_ticket_cost] = useState(240);
const [montegobay_ticket_cost] = useState(260);
/*Initialize variables with initial state*/
const [fname, setFname] = useState("");
const [lname, setLname] = useState("");
const [phone, setPhone] = useState("");
const [email, setEmail] = useState("");
const [adultText, setAdultText] = useState("Adult");
const [adultTotal, setAdultTotal] = useState(0);
const [childText, setChildText] = useState("Child");
const [childTotal, setChildTotal] = useState(0);
const [total, setTotal] = useState(0);
const [adult_tickets, setAdultTickets] = useState(0);
const [children_tickets, setChildrenTickets] = useState(0);
const [kingston, setKingston] = useState(false);
const [portland, setPortland] = useState(false);
const [negril, setNegril] = useState(false);
const [ochorios, setOchorios] = useState(false);
const [montegobay, setMontegobay] = useState(false);
/*get information sent through artificial URL*/
let location = useLocation();
/*Set initial values*/
const set_init_val = (state) => {
let priceCounter = 0;
/*Set checkboxes based on what is sent over*/
if (location.state != null) {
setAdultTickets((adult_tickets) => location.state.adult_s);
setChildrenTickets((children_tickets) => location.state.child_s);
if (location.state.destination_s === "kingston" || location.state.destination_s === "all") {
setKingston(true);
priceCounter += kingston_ticket_cost;
if (priceCounter == 0) {
alert("Error : state not updated");
}
}
if (location.state.destination_s === "portland" || location.state.destination_s === "all") {
setPortland(true);
priceCounter += portland_ticket_cost;
}
if (location.state.destination_s === "negril" || location.state.destination_s === "all") {
setNegril(true);
priceCounter += negril_ticket_cost;
}
if (location.state.destination_s === "ochorios" || location.state.destination_s === "all") {
setOchorios(true);
priceCounter += ochorios_ticket_cost;
}
if (location.state.destination_s === "montegobay" || location.state.destination_s === "all") {
setMontegobay(true);
priceCounter += montegobay_ticket_cost;
}
setAdultTotal((adultTotal) => adult_tickets * priceCounter);
setChildTotal((childTotal) => children_tickets * ((adultTotal / adult_tickets) / 2));
setTotal((total) => adultTotal + childTotal);
} else {
return
}
return total;
}
useEffect(() => {
set_init_val()
}, []);
return (
<>
<Header/>
<Container>
<h1 className="booking_title">Book Your Next Adventure</h1>
<Form>
<Row>
<Col style={{padding: "50px"}}>
<h1 className="formheader">Booking Information</h1>
<div style={{padding: "15px"}}>
<Form.Group className={"mb-3"} style={{fontWeight: "bold"}}>
<Form.Label>First Name</Form.Label>
<Form.Control placeholder={"First name"} style={{width: "500px"}}/>
</Form.Group>
<Form.Group className={"mb-3"} style={{fontWeight: "bold"}}>
<Form.Label>Last Name</Form.Label>
<Form.Control placeholder={"Last name"} style={{width: "500px"}}/>
</Form.Group>
<Form.Group className={"mb-3"} style={{fontWeight: "bold"}}>
<Form.Label>Phone</Form.Label>
<Form.Control name={"phone"} placeholder={"000-000-0000"}
style={{width: "500px"}}/>
</Form.Group>
<Form.Group className={"mb-3"} style={{fontWeight: "bold"}}>
<Form.Label>Email</Form.Label>
<Form.Control placeholder={"email#email.com"}
style={{width: "500px"}}/>
</Form.Group>
<Form.Label style={{fontWeight: "bold"}}>Destinations</Form.Label>
{['checkbox'].map((type) => (
<div key={`default-${type}`} className="mb-3">
<Form.Check
id={`default-${type}`}
label={`Kingston $180`}
checked={kingston}
onChange={(e) => setKingston(!kingston)}
/>
<Form.Check
id={`default-${type}`}
label={`Portland $200`}
checked={portland}
onChange={(e) => setPortland(!portland)}
/>
<Form.Check
id={`default-${type}`}
label={`Negril $280`}
checked={negril}
onChange={(e) => setNegril(!negril)}
/>
<Form.Check
id={`default-${type}`}
label={`Ocho Rios $240`}
checked={ochorios}
onChange={(e) => setOchorios(!ochorios)}
/>
<Form.Check
id={`default-${type}`}
label={`Montego Bay $260`}
checked={montegobay}
onChange={(e) => setMontegobay(!montegobay)}
/>
</div>
))}
<Row>
<Col>
<Form.Label style={{fontWeight: "bold"}}>Adult</Form.Label>
<Form.Select value={adult_tickets}
onChange={(e) => setAdultTickets(parseInt(e.target.value))}>
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</Form.Select>
</Col>
<Col>
<Form.Label style={{fontWeight: "bold"}}>Children</Form.Label>
<Form.Select value={children_tickets}
onChange={(e) => setChildrenTickets(parseInt(e.target.value))}>
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</Form.Select>
</Col>
<Col>
<Form.Label style={{fontWeight: "bold"}}>Date</Form.Label>
<Form.Control type={"date"}/>
</Col>
</Row>
</div>
</Col>
<Col className={"paycol"} style={{padding: "50px"}}>
<h1 className="formheader">Payment Information</h1>
<div className={"totals"} style={{padding: "15px"}}>
<Row>
<Col>{adultText}</Col>
<Col>${adultTotal}</Col>
</Row>
<Row>
<Col>{childText}</Col>
<Col>${childTotal}</Col>
</Row>
<Row>
<Col>Total</Col>
<Col>${total}</Col>
</Row>
</div>
<div style={{marginTop: "50px"}}>
<Form.Label style={{fontWeight: "bold"}}>Credit/Debit Card number</Form.Label>
<Form.Control placeholder={"0000 0000 0000 0000"}/>
<Row style={{marginTop: "50px"}}>
<Col>
<Form.Label style={{fontWeight: "bold"}}>Exp month</Form.Label>
<Form.Select>
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</Form.Select>
</Col>
<Col>
<Form.Label style={{fontWeight: "bold"}}>Exp Year</Form.Label>
<Form.Select>
<option value="2022">2022</option>
<option value="2023">2023</option>
<option value="2024">2024</option>
<option value="2025">2025</option>
<option value="2026">2026</option>
<option value="2027">2027</option>
<option value="2028">2028</option>
<option value="2029">2029</option>
<option value="2030">2030</option>
<option value="2031">2031</option>
<option value="2032">2032</option>
</Form.Select>
</Col>
<Col>
<Form.Label style={{fontWeight: "bold"}}>CVC</Form.Label>
<Form.Control placeholder={"000"}/>
</Col>
</Row>
</div>
<br/><br/>
<div className="checkbox pcheck">
<label htmlFor="destinations-1">
<input type="checkbox" id="cash"/>
<b> Pay with with cash</b> <br/><br/>
<h3>By paying with cash I agree to advise my tour guide 30 minutes ahead of time
that I need to complete payment</h3>
</label>
</div>
</Col>
</Row>
</Form>
</Container>
<Footer/>
</>
);
};
export default Bookings;

Related

What is the differences using another components or putting everything inside the parent component in terms of performance optimization in Reactjs?

Are there any differences between using MethodRow or putting everything inside the parent in terms of performance optimization? In my case, if I use MethodRow, rendering time is around 15 ms. On the otherhand not using MethodRow rendering time is around 75 ms. What are the reasons for this?
// PS: Using React Profiler
return (
<Card className="mb-3" data-testid="method-card">
<Card.Header>{header}</Card.Header>
{isActive ? (
<Card.Body>
<div className="form-horizontal">
<FormHeading />
{_.map(params, (param, paramKey) => {
// #ts-ignore
const { oneOf: { type: secondType } = emptyObject } =
PluginTypes.fromString(param.type) || emptyObject
const options = transformOptions(variables, param, secondType)
const { [paramKey]: value = '' } = assignees
// around 15ms
// return (
// <MethodRow
// key={paramKey}
// paramKey={paramKey}
// param={param}
// value={value}
// options={options}
// handleReturnVariableChange={handleReturnVariableChange}
// />
// )
// around 75ms
return (
<FormGroup key={paramKey} as={Row} className="mb-2">
<Col md={6}>
<FormLabel className="fw-bold">{`${paramKey} {${param.type}}`}</FormLabel>
</Col>
<Col md={6}>
<FormSelect
placeholder="select"
size="sm"
value={value === null ? '' : value}
onChange={(event: ChangeEvent<HTMLSelectElement>) =>
handleReturnVariableChange(event.target.value, paramKey)
}
>
<option value="">select</option>
{_.map(sortOptions(options), (_unused, variable) => (
<option key={variable} value={variable}>
{variable}
</option>
))}
</FormSelect>
</Col>
</FormGroup>
)
})}
</div>
</Card.Body>
) : null}
</Card>)
const MethodRow = ({ paramKey, param, value, options, handleReturnVariableChange }: any) => {
return (
<FormGroup as={Row} className="mb-2">
<Col md={6}>
<FormLabel className="fw-bold">{`${paramKey} {${param.type}}`}</FormLabel>
</Col>
<Col md={6}>
<FormSelect
placeholder="select"
size="sm"
value={value === null ? '' : value}
onChange={(event: ChangeEvent<HTMLSelectElement>) =>
handleReturnVariableChange(event.target.value, paramKey)
}
>
<option value="">select</option>
{_.map(sortOptions(options), (_unused, variable) => (
<option key={variable} value={variable}>
{variable}
</option>
))}
</FormSelect>
</Col>
</FormGroup>
)
}

React Multiselect package is sending [object, Object] instead of key and value

I am trying to pass data in my Django back end from react front end. I am able to pass the data using some Multi-select from react. But the problem is I am sending label and value but when I try to print my data in front end and check the data what it is passing I got the result like [object Object] instead of [mylabel MyValue]
and I just want to pass the option value. I am new to react so don't know much about setState things. Can someone help me to do this?
Or any other easy way to pass multiple data in my API it would be much appreciated like I select HD and SD then in my backend I should get both value.
#This is my react code check the deliveryOption, setDeliveryOption
import axios from "axios";
import React, { useState, useEffect } from 'react'
import { LinkContainer } from 'react-router-bootstrap'
import { Table, Button, Row, Col, Form } from 'react-bootstrap'
import { useDispatch, useSelector } from 'react-redux'
import { Link } from 'react-router-dom'
import FormContainer from '../components/FormContainer'
import { MultiSelect } from "react-multi-select-component";
import Select from 'react-select';
const UPLOAD_ENDPOINT = "http://127.0.0.1:8000/api/orders/create/products/";
const options = [
{ label: "HD 🍇", value: "HD" },
{ label: "SD 🥭", value: "SD" },
{ label: "DP 🍓", value: "DP" },
];
function VendorProductCreate() {
const [file, setFile] = useState(null);
const [name, setName] = useState("");
const [price, setPrice] = useState();
const [discount, setDiscount] = useState();
const [description, setDescription] = useState("");
const [subcategory, setSubcategory] = useState("");
const [countInStock, setCountInStock] = useState();
const [deliveryOption, setDeliveryOption] = useState([]);
// const [selected, setSelected] = useState([]);
const { userInfo } = useSelector((state) => state.userLogin);
const handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData();
formData.append("avatar", file);
formData.append("name", name);
formData.append("price", price);
formData.append("discount", discount);
formData.append("description", description);
formData.append("subcategory", subcategory);
formData.append("countInStock", countInStock);
formData.append("deliveryOption", deliveryOption);
// formData.append("selected", selected);
const resp = await axios.post(UPLOAD_ENDPOINT, formData, {
headers: {
"content-type": "multipart/form-data",
Authorization: `Bearer ${userInfo.token}`,
},
});
console.log(resp.status)
};
return (
<FormContainer>
<form onSubmit={handleSubmit}>
<br></br>
<Link to='/productlist/vendor'>
<Button
variant='outline-info'>Go Back</Button>
</Link>
<FormContainer>
<br></br>
<h1>Merchant Product Upload</h1></FormContainer>
<br></br>
<br></br>
<Form.Group controlId='name'>
<Form.Label><strong> Product Name </strong> </Form.Label>
<Form.Control
required
type='text'
onChange={(e) => setName(e.target.value)}
value={name}
// placeholder='Enter Name'
>
</Form.Control>
</Form.Group>
<br />
<Form.Group controlId='subcategory'>
<Form.Label>Choose a Category</Form.Label>
<Form.Select aria-label="Default select example"
required
type='text'
value={subcategory}
onChange={(e) => setSubcategory(e.target.value)}>
<option value="LPG Cylinder">LPG Cylinder</option>
<option value="LPG Gas">LPG Gas</option>
</Form.Select>
</Form.Group>
<br />
<Form.Group controlId='price'>
<Form.Label><strong>Price</strong> </Form.Label>
<Form.Control
required
type='number'
// placeholder='Enter Address'
onChange={(e) => setPrice(e.target.value)}
value={price}
>
</Form.Control>
</Form.Group>
<br />
<Form.Group controlId='discount'>
<Form.Label><strong> Set Discount (Optional) </strong> </Form.Label>
<Form.Control
type='number'
onChange={(e) => setDiscount(e.target.value)}
value={discount}
// placeholder='Enter Name'
>
</Form.Control>
</Form.Group>
<br />
<Form.Group controlId='countInStock'>
<Form.Label><strong> Stock </strong> </Form.Label>
<Form.Control
type='number'
onChange={(e) => setCountInStock(e.target.value)}
value={countInStock}
// placeholder='Enter Name'
>
</Form.Control>
</Form.Group>
<br />
<Form.Label><strong style={{marginLeft: 10}}>Product Picture</strong> </Form.Label>
<Form.Control
type='file'
id='image-file'
label='Choose File'
onChange={(e) => setFile(e.target.files[0])}
>
</Form.Control>
<br />
<Form.Group controlId='description'>
<Form.Label><strong> Description </strong> </Form.Label>
<Form.Control
required
type='text'
onChange={(e) => setDescription(e.target.value)}
value={description}
// placeholder='Enter Name'
>
</Form.Control>
</Form.Group>
<br />
{/* <Form.Group controlId='deliveryOption'>
<Form.Label>Choose a Delivery</Form.Label>
<Form.Select aria-label="Default select example"
required
multiple
type='checkbox'
onChange={(e) => setDeliveryOption(e.target.value)}>
<option value="HD">HD</option>
<option value="SD">SD</option>
</Form.Select>
</Form.Group>
<br /> */}
{/* <h1>Select Fruits</h1>
<pre>{JSON.stringify(selected)}</pre> */}
{/* <MultiSelect
options={options}
value={selected}
onChange={setSelected}
labelledBy="Select"
/> */}
<Select
isMulti
name="colors"
options={options}
className="basic-multi-select"
classNamePrefix="select"
value={deliveryOption}
onChange={setDeliveryOption}
/>
<br></br>
<FormContainer><FormContainer><FormContainer>
<Button variant='outline-primary' type="submit" className='btn-sm' >
Upload Product
</Button></FormContainer>
</FormContainer></FormContainer>
</form>
</FormContainer>
);
}
export default VendorProductCreate;
#this is backend code using Django rest
#api_view(['POST'])
#permission_classes([IsVendor])
def vendorCreateProduct(request):
data = request.data
user = request.user.vendor
print(data['deliveryOption'])
print(data['selected'])
product = Product.objects.create(
user=user,
name=data['name'],
old_price = data['price'],
discount = data['discount'],
image = data['avatar'],
countInStock = data['countInStock'],
subcategory = Subcategory.objects.get_or_create(name=data['subcategory'])[0],
description=data['description'],
delivery_option= DeliveryOption.objects.get_or_create(name=data['deliveryOption'])[0],
)
serializer = ProductSerializer(product, many=False)
return Response(serializer.data)
I just want to save some multiple choice field with multiple select option using Django and react if you know any other easy and good approach then share

ReferenceError: Cannot access 'steps' before initialization

I'm trying to make wizards in ReactJS. I'm following an online tutorial, however they haven't explained how to make it by multiple pages. So I tried my own way to apply it, but it didn't work.
Here is the code of the first page:
import React, { useState } from "react";
import { Button, Form } from "react-bootstrap";
import { Link } from "react-router-dom";
import "./style.css";
function NewGame() {
const [activeStep, setActiveStep] = useState(steps[0]);
const [steps, setSteps] = useState([
{
key: "firstStep",
label: "My First Step",
isDone: true,
component: firstStep,
},
]);
const index = steps.findIndex((x) => x.key === activeStep.key);
setSteps((prevStep) =>
prevStep.map((x) => {
if (x.key === activeStep.key) x.isDone = true;
return x;
})
);
const firstStep = () => {
return (
<div>
<div className="box">
<div className="steps">
<ul className="nav">
{steps.map((step, i) => {
return (
<li
key={i}
className={`${
activeStep.key === step.key ? "active" : ""
} ${step.isDone ? "done" : ""}`}
>
<div>
Step {i + 1}
<br />
<span>{step.label}</span>
</div>
</li>
);
})}
</ul>
</div>
<div className="step-component">{activeStep.component()}</div>
<div className="btn-component">
<input
type="button"
value="Back"
onClick={handleBack}
disabled={steps[0].key === activeStep.key}
/>
<input
type="button"
value={
steps[steps.length - 1].key !== activeStep.key
? "Next"
: "Submit"
}
onClick={handleNext}
/>
</div>
</div>
<Form className="column justify-content-center page">
<Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
<Form.Label>Benzersiz Ad</Form.Label>
<Form.Control as="textarea" rows={3} />
</Form.Group>
<Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
<Form.Label>Görünen İsim</Form.Label>
<Form.Control as="textarea" rows={3} />
</Form.Group>
<Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
<Form.Label>Oyun Açıklaması</Form.Label>
<Form.Control as="textarea" rows={3} />
</Form.Group>
<Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
<Form.Label>Oyun Türü</Form.Label>
<Form.Control as="textarea" rows={3} />
</Form.Group>
<Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
<Form.Label>Bireysel</Form.Label>
<Form.Control as="textarea" rows={3} />
</Form.Group>
<Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
<Form.Label>Oyun Durumu</Form.Label>
<Form.Control as="textarea" rows={3} />
</Form.Group>
<Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
<Form.Label>Açık</Form.Label>
<Form.Control as="textarea" rows={3} />
</Form.Group>
</Form>
<Link to="/PageTwo">
<Button className="button" variant="outline-secondary">
İ L E R İ
</Button>{" "}
</Link>
</div>
);
const handleNext = () => {
if (steps[steps.length - 1].key === activeStep.key) {
alert("You have completed all steps.");
}
setActiveStep(steps[index + 1]);
};
const handleBack = () => {
const index = steps.findIndex((x) => x.key === activeStep.key);
if (index === 0) return;
setSteps((prevStep) =>
prevStep.map((x) => {
if (x.key === activeStep.key) x.isDone = false;
return x;
})
);
setActiveStep(steps[index - 1]);
};
};
}
export default NewGame;
So when I run this code I have this error in the website:
ReferenceError: Cannot access 'steps' before initialization
NewGame
C:/Users/SAMSUNG/Documents/src/pages/NewGame.js:6
3 | import { Link } from "react-router-dom";
4 | import "./style.css";
5 | function NewGame() {
> 6 | const [activeStep, setActiveStep] = useState(steps[0]);
7 | const [steps, setSteps] = useState([
8 | {
9 | key: "firstStep",
Thank you!
The error is telling you that the variable steps is initialized on line 7, but you're using it on line 6 to set the initial value of the activeStep state variable. You cannot use a variable before it's initialized, hence the message "Cannot access 'steps' before initialization".
Move line 6 after the statement that begins on line 7.

How to show/hide a select input according to a value chosen in a previous select input reactjs?

I am new to reactjs, and here I have a form, and in that form I have an input select with two value options.
And the first value option should allow me to bring up a second input select with these value options, and the second nothing at all.
I made my form and for the first input select I manage to do an onChange method, to retrieve the chosen value, but now how to do a test on the chosen value, to display or not the second input select ?
And how to show or hide this second input select ?
My Form
// methode that retrieve the chosen value in input select
const handleOptionChange = (event: any) => {
console.log(event);
};
const FormContent = (props: any) => {
const { control, handleSubmit, errors } = useForm();
const { Option } = Select;
const onSubmit = handleSubmit((data) => {
console.log(data);
});
return (
<form onSubmit={onSubmit}>
<Row gutter={8}>
<Col md={12} lg={12} sm={24}>
<div className="ant-form-item">
<label className="label">Nom Utilisateur <span className="text-danger">*</span></label>
<Controller
// as={inputField("Nom Utilisateur")}
name="username"
control={control}
defaultValue={""}
rules={{ required: true }}
render={props => (<><Input name={props.name} defaultValue={props.value} className="ant-form-item-control" placeholder="Nom Utilisateur" /></>)}
/>
{errors.username && "First name is required"}
</div>
</Col>
<Col md={12} lg={12} sm={24}>
<div className="ant-form-item">
<label className="label">Mot de passe <span className="text-danger">*</span></label>
<Controller
// as={inputPassField()}
name="password"
control={control}
defaultValue={""}
rules={{ required: true }}
render={props => (<Input.Password placeholder="Mot de passe" />)}
/>
{errors.password && "First name is required"}
</div>
</Col>
</Row>
<Row gutter={8}>
<Col md={12} lg={12} sm={24}>
<div className="ant-form-item">
<label className="label">Profile<span className="text-danger">*</span></label>
<Controller
name="profile"
control={control}
defaultValue={""}
rules={{ required: true }}
render={({ onChange, value, name }) => (
<Select
showSearch
placeholder="Select a person"
onChange={(event) => {
onChange(event)
handleOptionChange(event)
}}
value={value ? value : ""}
// name={name}
optionFilterProp="children"
filterOption={(input, option: any) =>
option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}>
<option key="b2b_user" value="B2B_CLIENT">B2B_USER</option>
<option key="app_user" value="APPLICATION_USER">USER_SIMPLE</option>
</Select>)}
/>
{errors.profile && "Profile is required"}
</div>
</Col>
</Row>
<Row gutter={8}>
<Col md={12} lg={12} sm={24}>
<Flex alignItems="center" justifyContent="center">
<Button onClick={() => props.onClose()} icon={<CloseOutlined />} size="small" className="mr-3" type="text">Annuler</Button>
<Button icon={<CheckCircleOutlined />} type='primary' htmlType='submit'>
Valider
</Button>
</Flex>
</Col>
</Row>
</form>);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Second input to show/hide
export const SelectCompanyField = () => {
const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(10);
const { data, error } = useSWR<ServerResponse, any>(companyUrls.base + `?page:${page}&perPage:${perPage}`, url => getDataByParams(companyUrls.base, { page: '' + page, perPage: '' + perPage }));
console.log("Data", data, "Error", error);
console.log(data?.entities);
return (
<Select
showSearch
placeholder="Choisir une compagnie"
optionFilterProp="children"
filterOption={(input, option: any) =>
option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
{data?.entities.map(d => (
<option value={d.index} key={d.id} >
{d.name}
</option>
))}
</Select>
);
};
// the second input select to show/hide
<Col md={24} lg={24} sm={24}>
<div className="ant-form-item">
<label className="label">Compagnie <span className="text-danger">*</span></label>
<Controller
as={SelectCompanyField()}
name="company"
control={control}
defaultValue={""}
rules={{ required: false }}
/>
{errors.company && "Company is required"}
</div>
</Col>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Thanks
Something like...
const [firstOptionValue, setFirstOptionValue] = useState(null)
const handleOptionChange = (event: any) => {
setFirstOptionValue(event.target.value)
};
Then when you want to conditionally render the second select...
{firstOptionValue && <SecondSelectContainer/>}
So whatever is in SecondSelectContainer will only render if firstOptionValue is not falsey.

Not sure how to display my api data onto my react component in my react app

I was wondering if someone could help me out with my problem.
First let me display my code:
import React, { useState } from "react"
import { Form, Card, Button, Jumbotron, Container, Col, Row, CardDeck } from "react-bootstrap"
import Navibar from "../components/navbar"
import axios from "axios"
function Home(){
const [type, setType] = useState()
const [genrelist, setGenrelist] = useState()
const [start_year, setStart_year] = useState()
const [start_rating, setStart_rating] = useState()
const handleSubmit = e => {
e.preventDefault()
const options = {
method: 'GET',
url: 'https://unogsng.p.rapidapi.com/search',
params: {
type: type,
genrelist: genrelist,
start_year: start_year,
start_rating: start_rating,
end_rating: "10",
orderby: 'rating',
limit: '100',
countrylist: '78',
audio: 'english',
end_year: '2020'
},
headers: {
'x-rapidapi-key': process.env.REACT_APP_RAPID_API_KEY,
'x-rapidapi-host': 'unogsng.p.rapidapi.com'
}
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
}
return (
<>
<Navibar />
<Container className="d-flex align-items-center justify-content-center mt-5"
style={{ minHeight: "100vh" }}>
<div className="w-100" style={{ maxWidth: "800px" }}>
<Jumbotron>
<Row>
<Col md={6}>
<Form style={{ maxWidth: "400px" }} onSubmit={handleSubmit} >
<Form.Group>
<Form.Row>
<Form.Label column="lg" lg={2}>
Genre
</Form.Label>
<Col xs={7}>
<Form.Control size="lg" as="select" placeholder="Large text" name="genrelist" onChange={e => setGenrelist(e.target.value)} >
<option value="899">Action and Adventure</option>
<option value="4698">Animation</option>
<option value="1492">Sci-Fi and Fantasy</option>
<option value="9744">Fantasy</option>
<option value="7424">Anime</option>
<option value="783">Children and Family</option>
<option value="9736">Comedies</option>
<option value="8673">Documentaries</option>
<option value="5763">Dramas</option>
<option value="9327">Sports</option>
<option value="8711">Horror Films</option>
<option value="26126">Crime Docuseries</option>
<option value="7992">TV Animated Comedies</option>
</Form.Control>
</Col>
</Form.Row>
</Form.Group>
<br />
<fieldset>
<Form.Group as={Row}>
<Form.Label as="legend" column="lg" lg={2}>
Type
</Form.Label>
<Col sm={10}>
<Form.Check
id="movie"
name="type"
value="movie"
type="radio"
label="Movies"
onChange={e => setType(e.target.value)}
/>
<Form.Check
type="radio"
label="Tv Shows"
name="type"
id="series"
value="series"
onChange={e => setType(e.target.value)}
/>
</Col>
</Form.Group>
</fieldset>
<br />
<Form.Group>
<Form.Row>
<Form.Label column="lg" lg={2}>
IMDB Rating
</Form.Label>
<Col xs={7}>
<Form.Control size="lg" as="select" name="start_rating" onChange={e => setStart_rating(e.target.value)} >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</Form.Control>
</Col>
</Form.Row>
</Form.Group>
<br />
<Form.Group>
<Form.Row>
<Form.Label column="lg" lg={2}>
Start Year
</Form.Label>
<Col xs={7}>
<Form.Control size="lg" as="input" name="start_year" onChange={e => setStart_year(e.target.value)}/>
</Col>
</Form.Row>
</Form.Group>
<Button type="submit" variant="primary" className="w-100">Generate!</Button>
</Form>
</Col>
<Col md={6}>
<CardDeck >
<Card>
<Card.Img variant="top" src="https://www.placehold.it/200x200" />
<Card.Body>
<Card.Title>Card title</Card.Title>
<Card.Text>
</Card.Text>
</Card.Body>
</Card>
</CardDeck>
</Col>
</Row>
</Jumbotron>
</div>
</Container>
</>
)
}
export default Home
So basically this page manipulates the API call with whatever data the user inputs into the form. When the user hits the generate button, it console.logs the api data with the relevant information the user selected with the form. Now I want to display one item in the array that the api calls randomly to the card at the bottom of the code. But I'm not sure how to take the information from the handlesumbit function and place it onto the card. If anyone has any advice it would be greatly appreciated!
I would add a card information variable as a state :
const [cardDetails, setCardDetails] = React.useState("")
In your displayed card :
<Card.Text> {cardDetails} </Card.Text>
Then, when your function returns a value, set the value in the state :
axios.request(options).then(function (response) {
console.log(response.data);
setCardDetails(response.data) // The card details coming from your API !
}).catch(function (error) {
console.error(error);
});

Resources