i have created a demo file where i have set up a dispatcher and same is been connecting through connect function to the App component.
But while I'm trying to access props in component, its showing me blank rather it should have a dispatch function.
Please assist to get through.
import App from "../Components/App";
import { connect } from "react-redux";
import { buyCartAction } from "../Services/Action";
const mapStateToProps =()=>{
}
const mapDispatchToProps = dispatch => (
{ buyThisProduct: data => dispatch(buyCartAction(data)) }
)
export default connect(mapStateToProps, mapDispatchToProps)(App)`
import React from "react"
function App(props) {
console.log(props)
return (
<>
<h1 className="heading">Good Day Page</h1>
<div className="cart_bar">
<img className="img_scale" src="https://images.news18.com/ibnlive/uploads/2021/08/1628224744_hp-envy-14-laptop-1600x900.jpg" alt="Lenovo Laptop" />
<div className= "child_cart">
<p className="info_bar">Lenovo Probook 15 series </p>
<span className="info_bar_price">Price at just Rs: 37000/-</span>
<br />
<button className="btn_buy"}>Buy</button>
</div>
</div>
</>
)
}
export default App;
Action creator as below:
import { buy } from "../Constants"
export const buyCartAction =(data) =>{
return{
type: buy,
data: data
}
}
Console output as below.
enter image description here
Related
I´m new to NextJS and React at all so I ask for your forgiveness.
I want to know how to pass an users written text from an input field (inside of Header) into the getStaticProbs function of a specific page via the react context api.
I tried the following source but it doesn`t work - it throws out an error that my way to build leads to an invalid hook call.
Here is my context source:
import React, { createContext, useState } from 'react';
export const SearchContext = createContext();
export const SearchProvider = ({ children }) => {
const [keyword, setKeyword] = useState('');
return (
<SearchContext.Provider
value={{
keyword,
setKeyword,
}}
>
{children}
</SearchContext.Provider>
);
};
to fetch the written string of SearchBar.js:
import React, { useContext, useState } from 'react';
import { useRouter } from 'next/router';
import Image from 'next/image';
import loupe from '../public/images/loupe.png';
import { SearchContext } from '../lib/searchCtx';
const SearchBar = () => {
const search = useContext(SearchContext);
const router = useRouter();
const submitAction = (e) => {
e.preventDefault();
router.push(`/searchResults`);
};
return (
<div className={styles.searchBar}>
<input
type='text'
placeholder='Suche...'
onChange={(e) => search.setKeyword(e.target.value)}
/>
<button className={styles.searchBtn} type='submit' onClick={submitAction}>
<Image src={loupe} alt='' />
</button>
</div>
);
};
export default SearchBar;
and pass it over _app.js:
import Header from '../components/Header';
import Footer from '../components/Footer';
import { SearchProvider } from '../lib/searchCtx';
function MyApp({ Component, pageProps }) {
return (
<>
<SearchProvider>
<Header />
<Component {...pageProps} />
</SearchProvider>
<Footer />
</>
);
}
}
export default MyApp;
to get the value into getStaticProbs of searchResults.js:
import { useEffect, useState, useContext } from 'react';
import { fetchData } from '../lib/utils';
import styles from '../styles/Playlist.module.scss';
import Image from 'next/image';
import { SearchContext } from '../lib/searchCtx';
export default function SearchResults({ videos }) {
console.log(videos);
const sortedVids = videos
.sort((a, b) =>
Number(
new Date(b.snippet.videoPublishedAt) -
Number(new Date(a.snippet.videoPublishedAt))
)
)
return (
<>
<div className={`${styles.playlist_container} ${styles.search}`}>
<h1>Search results</h1>
{sortedVids
.map((vid, id) => {
return (
<div className={styles.clip_container}>
<Image
className={styles.thumbnails}
src={vid.snippet.thumbnails.medium.url}
layout='fill'
objectFit='cover'
alt={vid.snippet.title}
/>
</div>
<div className={styles.details_container}>
<h3>{vid.snippet.title}</h3>
</div>
);
})}
</div>
</>
);
}
export async function getStaticProps() {
const search = useContext(SearchContext);
const { YOUTUBE_KEY } = process.env;
const uploadsURL = `https://youtube.googleapis.com/youtube/v3/search?part=snippet&channelId=UCbqKKcML7P4b4BDhaqdh_DA&maxResults=50&key=${YOUTUBE_KEY}&q=${search.keyword}`;
async function getData() {
const uploadsData = fetchData(uploadsURL);
return {
videos: await uploadsData,
};
}
const { videos } = await getData();
return {
revalidate: 86400,
props: {
videos: videos.items,
},
};
}
Would you help me by 1) telling me the main failure I did and 2) providing me a working source?
How can I achieve it to get the keyword from SearchContext into the uploadsURL (inside of getStaticProbs) or isn`t it possible?
Thanks in advance!!
You can create a dynamic pages under your page folder one called say index.js and one called [slug].js (all under one folder) In the index page you can have your normal search input, when the users submit the query you can do
<a
onClick={() =>
router
.push(`/movies/${search.keyword}`)
.then(() => window.scrollTo(0, 0))}>
search
</a>
and in your [slug].js page you can retrieve that information like so
export async function getServerSideProps(pageContext) {
const pageQuery = pageContext.query.slug;
const apiCall= await fetch(
``https://youtube.googleapis.com/youtube/v3/search?part=snippet&channelId=UCbqKKcML7P4b4BDhaqdh_DA&maxResults=50&key=${YOUTUBE_KEY}&q=${pageQuery}`
);
const results = await apiCall.json();
return {
props: {
data: results,
},
};
}
I don't know if this will work for you but is a solution
Error I am getting: ./src/components/IconsOne.js Attempted import error: 'TiHome' is not exported from 'react-icons/fa'.
IconsOne.js:
import { TiHome } from 'react-icons/fa';
const IconsOne = () => {
return (
<div className="homeIcon">
<h3>
<TiHome />
</h3>
</div>
)
}
export default IconsOne
App.js
import './App.css';
import IconsOne from "./components/IconsOne";
function App() {
return (
<div className="App">
<Router>
<IconsOne />
</Router>
</div>
);
}
export default App;
I am trying to build a navbar and the first step is to render a home icon. I used this page for documentation on importing icons for react: https://react-icons.github.io/react-icons/ and the name of the Icon that I'm trying to import is TiHome
The link to the icon is: https://react-icons.github.io/react-icons/search?q=tihome
Thank you.
The problem is fa, that is not the path for Typicons but for FontAwesome, so if you want TiHome from Typicons then according to react-icons you must use instead the ti path, so:
import { TiHome } from 'react-icons/ti';
const IconsOne = () => {
return (
<div className="homeIcon">
<h3>
<TiHome />
</h3>
</div>
)
}
export default IconsOne
Am a newbie in react, so pardon me if am unable to fully explain the problem am facing, but after google searching, I came to understand that the object am trying to map is not an array(which am not sure is the case this time around because, all the examples I see online is the same and I take my time for the past 4weeks to diligently follow up the examples I see online but I cant just figure my react app to work
In
catalog.js
(this is the react component script, located in the component folder), I have this
import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as catalogActions from "../../actions/catalog";
import ProductImage from "./ProductImage";
import ProductThumbs from "./ProductThumbs";
export class CatalogComponent extends Component {
componentDidMount() {
this.props.fetchCatalog();
}
render() {
const { catalogs, selectProduct, selectedProduct } = this.props;
return (
//let { catalogs } = this.props;
<div>
<h1>Catalog Field</h1>
<div className="image-gallery" hidden={!selectedProduct}>
<ProductImage product={selectedProduct} />
<ProductThumbs selectProduct={selectProduct} catalogs={catalogs} />
</div>
</div>
);
}
}
export default connect(
state => ({
catalogs: state.catalogs,
selectedProduct: state.selectedProduct
}),
dispatch => bindActionCreators(catalogActions, dispatch)
)(CatalogComponent);
And in
productImage.js
I have this
import React from “react”;
export default function ProductImage({ product }) {
return (
<div className="gallery-image">
<div>{product ? <img src={product} alt={"gbenga"} /> : null}</div>
</div>
);
}
And
productThumbs.js
has this
import React from "react";
export default function ProductThumbs({ catalogs, selectProduct }) {
return (
<div className="image-scroller">
{catalogs.map((product, index) => (
<div key={index} onClick={selectProduct.bind(this, product)}>
<img src={product} alt={"gbenga now"} />
</div>
))}
</div>
);
}
The problem is in this script as it says
catalogs.map is not a function
this is what is in the reducer
import { CATALOGS_RECEIVED } from "../constants/catalog";
import { SELECT_PRODUCT } from "../constants/catalog";
export default function catalogs(state = { catalogs: [] }, action) {
switch (action.type) {
case CATALOGS_RECEIVED:
console.log(JSON.stringify(action.catalogs));
return { ...state, catalogs: action.catalogs };
case SELECT_PRODUCT:
return { ...state, selectedProduct: action.product };
default:
return state;
}
}
I don't think the problem has anything to do with
sagas
I am trying to build a single-page React app, which loads content from an API using Axios.
I have created the component called "Importapi" and called it in the App.js file as yet nothing is showing up.
Does anyone have an idea as to why this is happening?
Importapi - Import Component
import React, { Component } from 'react';
import axios from "axios";
import "./index.css";
export class Importapi extends Component {
constructor() {
super();
this.state = {
trails: [],
}
//this.handleSubmit = this.handleSubmit.bind(this);
};
componentDidMount() {
axios.get("https://www.hikingproject.com/data/get-trails?lat=46.589519&lon=7.912295&maxDistance=100&maxResults=15&key=200490043-7294b2e6976c168d4e44877bf48ef553")
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<div className="container2">
<div className="container1">
{this.state.trails}
</div>
</div>
)
};
};
export default Importapi;
App.js - Single page React App
import React from 'react';
import logo from './logo.png';
import './App.css';
import Import from './import.js';
import Importapi from './axios-api'
function App() {
return (
<div className="App">
<header>
<title>Hikeero</title>
</header>
<nav>
<div className="nav-bar logo">
<button>BACK</button>
</div>
<div className="nav-bar items">
</div>
<button> HOME </button>
</nav>
<div align="right" >
<br/>
</div>
<h1>Hikeero.</h1>
<Import />
<Importapi />
<header className="App-header">
<a
className="App-link"
href="/import.js/"
target="_blank"
rel="noopener noreferrer"
>
<br/>
<br/>
<br/>
Click to Start
</a>
</header>
</div>
);
}
export default App;
There are no errors, just the API information isn't showing up.
You have to do this.setState({ trails : response.data }) just below console.log(response.data); to show the content on component. Thus the API response will be set into state with key name of trails.
componentDidMount() {
axios.get("https://www.hikingproject.com/data/get-trails?lat=46.589519&lon=7.912295&maxDistance=100&maxResults=15&key=200490043-7294b2e6976c168d4e44877bf48ef553")
.then(response => {
// here once you receive response
// put the response data into state of the component
// as written below
this.setState({trails: response.data})
})
.catch(error => {
console.log(error);
});
}
Here I let user to view the details of the event. There will be a button at the end of the event details for them to delete the event. However, how should I go about doing this?
Should I implement the delete function here in the viewing event details file? Or should I create another .jsx file that handles the delete? The delete.jsx file below contains the handleDelete method that will delete the event from the redux store, which then updates the delete to the firestore
VIEWING EVENT DETAILS FILE
import React from "react";
import { connect } from "react-redux";
import { firestoreConnect } from "react-redux-firebase";
import { compose } from "redux";
import { Redirect } from "react-router-dom";
import moment from "moment";
import DeleteEvent from "./DeleteEvent";
const EventDetails = props => {
const { event, auth } = props;
if (!auth.uid) return <Redirect to="/signin" />;
if (event) {
return (
<div className="container section project-details">
<div className="card z-depth-0">
<div className="card-content">
<span className="card-title">Subject: {event.subject}</span>
<p>Venue: {event.venue}</p>
<p>Time: {event.time}</p>
<p>Description: {event.description}</p>
<p>Class Size: {event.size}</p>
</div>
<div className="card-action grey lighten-4 grey-text">
<div>
Tutor: {event.authorFirstName} {event.authorLastName}
</div>
<div>
Time of class created:
{moment(event.createdAt.toDate()).calendar()}
</div>
<DeleteEvent event={event} />
</div>
</div>
</div>
);
} else {
return (
<div className="container centre">
<p>Loading event....</p>
</div>
);
}
};
const mapStateToProps = (state, ownProps) => {
const id = ownProps.match.params.id;
const events = state.firestore.data.events;
const event = events ? events[id] : null;
return {
event: event,
auth: state.firebase.auth
};
};
export default compose(
connect(mapStateToProps),
firestoreConnect([
{
collection: "events"
}
])
)(EventDetails);
DELETE.JSX FILE
import React, { Component } from "react";
import { connect } from "react-redux";
import { Redirect } from "react-router-dom";
import { deleteEvent } from "../../store/actions/eventActions";
const DeleteEvent = ({ event }) => {
const handleDelete = e => {
e.preventDefault();
this.props.deleteEvent(event);
//this.props.history.push("/"); // redirect to homepage after deletion
};
return (
<div>
<button onClick={this.handleDelete} className="btn green z-depth-0">
Delete
</button>
</div>
);
};
const mapDispatchToProps = dispatch => {
return {
deleteEvent: event => dispatch(deleteEvent(event))
};
};
export default connect(null, mapDispatchToProps)(DeleteEvent);