How do I implement the search via backend query using Next js & Typescript?
Answered
Glen of Imaal Terrier posted this in #help-forum
Glen of Imaal TerrierOP
Hi everyone.
I want to implement a simple string search that query's the API for the result. I'm currently stuck.
"use client";
import { ChangeEvent, useState } from "react";
import axios, { AxiosResponse } from "axios";
export const NameSearch = async () => {
const [title, setTitle] = useState("");
const [result, setResult] = useState<string | null>(null);
const handleOnchange = (e: ChangeEvent<HTMLInputElement>): void => {
setTitle(e.target.value);
};
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const url = "https://search-practice-backend.vercel.app/api/v1/search";
try {
const { data }: AxiosResponse = await axios.get(url, {
params: { title },
});
setResult(data.final);
} catch (error) {
console.log(error);
}
}
return (
#Unknown Channel
<form onSubmit={handleSubmit}>
<input
type="text"
name="title"
onChange={handleOnchange}
value={title}
/>
<button type="submit">Search for title</button>
</form>
<div>{result}</div>
</>
);
};
type AllData = {
_id: string;
title: string;
cost: number;
promote: boolean;
grade: number;
madeAt: string;
seller: string;
};
This is the structure of the data that the title search is attempted
{"final":[{"_id":"648d124e7111d378381e1d6d","title":"Movie","cost":452,"promote":true,"grade":3,"madeAt":"2023-06-17T01:54:17.725Z","seller":"big mike","v":0},{"_id":"648d124e7111d378381e1d6e","title":"Clock","cost":5,"promote":false,"grade":2,"madeAt":"2023-06-17T01:54:17.725Z","seller":"don","v":0}],"nbHits":10}
I want to implement a simple string search that query's the API for the result. I'm currently stuck.
"use client";
import { ChangeEvent, useState } from "react";
import axios, { AxiosResponse } from "axios";
export const NameSearch = async () => {
const [title, setTitle] = useState("");
const [result, setResult] = useState<string | null>(null);
const handleOnchange = (e: ChangeEvent<HTMLInputElement>): void => {
setTitle(e.target.value);
};
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const url = "https://search-practice-backend.vercel.app/api/v1/search";
try {
const { data }: AxiosResponse = await axios.get(url, {
params: { title },
});
setResult(data.final);
} catch (error) {
console.log(error);
}
}
return (
#Unknown Channel
<form onSubmit={handleSubmit}>
<input
type="text"
name="title"
onChange={handleOnchange}
value={title}
/>
<button type="submit">Search for title</button>
</form>
<div>{result}</div>
</>
);
};
type AllData = {
_id: string;
title: string;
cost: number;
promote: boolean;
grade: number;
madeAt: string;
seller: string;
};
This is the structure of the data that the title search is attempted
{"final":[{"_id":"648d124e7111d378381e1d6d","title":"Movie","cost":452,"promote":true,"grade":3,"madeAt":"2023-06-17T01:54:17.725Z","seller":"big mike","v":0},{"_id":"648d124e7111d378381e1d6e","title":"Clock","cost":5,"promote":false,"grade":2,"madeAt":"2023-06-17T01:54:17.725Z","seller":"don","v":0}],"nbHits":10}
Answered by Glen of Imaal Terrier
This fix works
"use client";
import React, { useState, useEffect } from "react";
import getAllData from "@/lib/getAllData";
const NameSearch: React.FC = () => {
const [searchTerm, setSearchTerm] = useState("");
const [searchResults, setSearchResults] = useState<AllData[]>([]);
const handleSearch = async () => {
try {
const results = await getAllData(searchTerm);
setSearchResults(results);
} catch (error) {
console.error("Error searching:", error);
}
};
return (
<div>
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<button onClick={handleSearch}>Search</button>
<ul>
{searchResults.map((result) => (
<div key={result._id}>
<li>{result.title}</li>
<li>{result.cost}</li>
</div>
))}
</ul>
</div>
);
};
export default NameSearch;
import axios, { AxiosError } from "axios";
export default async function getAllData(searchTerm?: string) {
const url = "https://search-practice-backend.vercel.app/api/v1/search";
const config = searchTerm ? { params: { title: searchTerm } } : {};
try {
const { data } = await axios.get(url, config);
return data.final as AllData[];
} catch (error: unknown) {
if (error instanceof AxiosError) {
console.log(error.response);
}
throw error;
}
}
"use client";
import React, { useState, useEffect } from "react";
import getAllData from "@/lib/getAllData";
const NameSearch: React.FC = () => {
const [searchTerm, setSearchTerm] = useState("");
const [searchResults, setSearchResults] = useState<AllData[]>([]);
const handleSearch = async () => {
try {
const results = await getAllData(searchTerm);
setSearchResults(results);
} catch (error) {
console.error("Error searching:", error);
}
};
return (
<div>
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<button onClick={handleSearch}>Search</button>
<ul>
{searchResults.map((result) => (
<div key={result._id}>
<li>{result.title}</li>
<li>{result.cost}</li>
</div>
))}
</ul>
</div>
);
};
export default NameSearch;
import axios, { AxiosError } from "axios";
export default async function getAllData(searchTerm?: string) {
const url = "https://search-practice-backend.vercel.app/api/v1/search";
const config = searchTerm ? { params: { title: searchTerm } } : {};
try {
const { data } = await axios.get(url, config);
return data.final as AllData[];
} catch (error: unknown) {
if (error instanceof AxiosError) {
console.log(error.response);
}
throw error;
}
}
1 Reply
Glen of Imaal TerrierOP
This fix works
"use client";
import React, { useState, useEffect } from "react";
import getAllData from "@/lib/getAllData";
const NameSearch: React.FC = () => {
const [searchTerm, setSearchTerm] = useState("");
const [searchResults, setSearchResults] = useState<AllData[]>([]);
const handleSearch = async () => {
try {
const results = await getAllData(searchTerm);
setSearchResults(results);
} catch (error) {
console.error("Error searching:", error);
}
};
return (
<div>
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<button onClick={handleSearch}>Search</button>
<ul>
{searchResults.map((result) => (
<div key={result._id}>
<li>{result.title}</li>
<li>{result.cost}</li>
</div>
))}
</ul>
</div>
);
};
export default NameSearch;
import axios, { AxiosError } from "axios";
export default async function getAllData(searchTerm?: string) {
const url = "https://search-practice-backend.vercel.app/api/v1/search";
const config = searchTerm ? { params: { title: searchTerm } } : {};
try {
const { data } = await axios.get(url, config);
return data.final as AllData[];
} catch (error: unknown) {
if (error instanceof AxiosError) {
console.log(error.response);
}
throw error;
}
}
"use client";
import React, { useState, useEffect } from "react";
import getAllData from "@/lib/getAllData";
const NameSearch: React.FC = () => {
const [searchTerm, setSearchTerm] = useState("");
const [searchResults, setSearchResults] = useState<AllData[]>([]);
const handleSearch = async () => {
try {
const results = await getAllData(searchTerm);
setSearchResults(results);
} catch (error) {
console.error("Error searching:", error);
}
};
return (
<div>
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<button onClick={handleSearch}>Search</button>
<ul>
{searchResults.map((result) => (
<div key={result._id}>
<li>{result.title}</li>
<li>{result.cost}</li>
</div>
))}
</ul>
</div>
);
};
export default NameSearch;
import axios, { AxiosError } from "axios";
export default async function getAllData(searchTerm?: string) {
const url = "https://search-practice-backend.vercel.app/api/v1/search";
const config = searchTerm ? { params: { title: searchTerm } } : {};
try {
const { data } = await axios.get(url, config);
return data.final as AllData[];
} catch (error: unknown) {
if (error instanceof AxiosError) {
console.log(error.response);
}
throw error;
}
}
Answer