I have a simple question.
I want to run the function I created in App.js in a different screen.
Each screen is connected to an AppContainer in context.
I'm going to use state on another screen, but I do not know how to do it.
Can you give me a simple example?
_setDefaultLocation = locationKey => {
console.log("call _setDefaultLocation function");
this.setState({ defaultLocation: locationKey });
console.log(this.state.defaultLocation);
this._getCurrent(locationKey);
};
The above function is called this.props._setDefaultLocation (); I tried to do this and it did not work.
import React from "react";
const WeatherContext = React.createContext();
function withWeather(WrappedComponent) {
return function withContext(props) {
return (
<WeatherContext.Consumer>
{value => <WrappedComponent value={value} {...props} />}
</WeatherContext.Consumer>
);
};
}
export { WeatherContext, withWeather };
Context is used to make it like that.
You can use global keyword to make your function global. Then you can use it in any screen.
For example, assume that you have a function is called 'myFunction'. You can implement your function in App.js as following.
global.myFunction = () => {
console.warn('I am a global function...')
// your function body
};
Then you can call this function in any screen just like other function calling..
In your case your function can implement in this format.
global._myFunction = locationKey => {
console.warn('I am a global function...')
// your function body
};
And when you are calling the function call it as _myFunction(locationKey).
NOTE: 'locationKey' is the parameter that you should pass for your function.
Think this solution will help you.
Related
I'm working on an open-source project and have encountered a bug. I'm not able to navigate the dropdown list items using the keyboard (arrow key/tab). I've written the keyboard-navigation logic, but not quite sure of how to implement it. Below is the code snippet.
.
.
.
const TopNavPopoverItem: FC<ComponentProps> = ({closePopover, description, iconSize, iconType, title, to}) => {
const history = useHistory();
const handleButtonClick = (): void => {
history.push(to);
closePopover();
};
const useKeyPress = function (targetKey: any) { // where/how am I supposed to use this function?
const [keyPressed, setKeyPressed] = useState(false);
function downHandler(key: any) {
if (key === targetKey) {
setKeyPressed(true);
}
}
const upHandler = (key: any) => {
if (key === targetKey) {
setKeyPressed(false);
}
};
React.useEffect(() => {
window.addEventListener('keydown', downHandler);
window.addEventListener('keyup', upHandler);
return () => {
window.removeEventListener('keydown', downHandler);
window.removeEventListener('keyup', upHandler);
};
});
return keyPressed;
};
return (
<button className="TopNavPopoverItem" onClick={handleButtonClick}>
<Icon className="TopNavPopoverItem__icon" icon={iconType} size={iconSize} />
<div className="TopNavPopoverItem__right">
<span className="TopNavPopoverItem__title">{title}</span>
<span className="TopNavPopoverItem__description">{description}</span>
</div>
</button>
);
};
Any workaround or fixes?
Thanks in advance.
A custom hook should always be defined at the top level of your file. It cannot be inside of a component. The component uses the hook, but doesn't own the hook.
You have a hook which takes a key name as an argument and returns a boolean indicating whether or not that key is currently being pressed. It's the right idea, but it has some mistakes.
When you start adding better TypeScript types you'll see that the argument of your event listeners needs to be the event -- not the key. You can access the key as a property of the event.
(Note: Since we are attaching directly to the window, the event is a DOM KeyboardEvent rather than a React.KeyboardEvent synthetic event.)
Your useEffect hook should have some dependencies so that it doesn't run on every render. It depends on the targetKey. I'm writing my code in CodeSandbox where I get warnings about "exhaustive dependencies", so I'm also adding setKeyPressed as a dependency and moving the two handlers inside the useEffect.
I see that you have one handler as function and one as a const. FYI it really doesn't matter which you use in this case.
Our revised hook looks like this:
import { useState, useEffect } from "react";
export const useKeyPress = (targetKey: string) => {
const [keyPressed, setKeyPressed] = useState(false);
useEffect(
() => {
const downHandler = (event: KeyboardEvent) => {
if (event.key === targetKey) {
setKeyPressed(true);
}
};
const upHandler = (event: KeyboardEvent) => {
if (event.key === targetKey) {
setKeyPressed(false);
}
};
// attach the listeners to the window.
window.addEventListener("keydown", downHandler);
window.addEventListener("keyup", upHandler);
// remove the listeners when the component is unmounted.
return () => {
window.removeEventListener("keydown", downHandler);
window.removeEventListener("keyup", upHandler);
};
},
// re-run the effect if the targetKey changes.
[targetKey, setKeyPressed]
);
return keyPressed;
};
I don't know you intend to use this hook, but here's a dummy example. We show a red box on the screen while the spacebar is pressed, and show a message otherwise.
Make sure that the key name that you use when you call the hook is the correct key name. For the spacebar it is " ".
import { useKeyPress } from "./useKeyPress";
export default function App() {
const isPressedSpace = useKeyPress(" ");
return (
<div>
{isPressedSpace ? (
<div style={{ background: "red", width: 200, height: 200 }} />
) : (
<div>Press the Spacebar to show the box.</div>
)}
</div>
);
}
CodeSandbox Link
The two of the following result in different things although they look like the same thing.
1
const addBlogPost = dispatch => {
return () => {
dispatch({type: 'add_blogpost'});
}
};
2
const addBlogPost = dispatch => dispatch({type: 'add_blogpost'});
Could anyone point out how are they different?
You can use this site to compile es6 arrow functions to vanilla JS to easily see the difference.
The first one compiles to this
var addBlogPost = function addBlogPost(dispatch) {
return function () {
dispatch({
type: 'add_blogpost'
});
};
};
While the second compiles to this
var addBlogPost = function addBlogPost(dispatch) {
return dispatch({
type: 'add_blogpost'
});
};
The first returns a function that has a dispatch while the second one returns a dispatch directly.
The result will always be the same as both functions are retuning the same thing.
The only difference is:
In the first function, you're returning a function which returns an object that returns dispatch function.
In the second function, you're returning your dispatch function directly.
I'm calling a function to get a response from Http.get() request.
My data retrieve function is this one:
getCharacterDetail(characterId: number) {
return this.http.get(this.characterDetailApiUrl + characterId)
.subscribe(res =>
console.log(res.json())
);
}
Now I have to show this data into a modal window. No idea of what to do.
ng-bootrstrap would be a good option because modal component is available where you could pass the necessary data as an input to the component.
example
Using the code you've provided, here's a rough estimate of what you might be looking for.
app.controller('characterController', function ($scope, $http) {
$scope.getCharacterDetail = function (number) {
return $http.get(this.characterDetailApiUrl + characterId)
.subscribe(res =>
console.log(res.json())
);
}
});
Sometimes my Redux selectors are quite complicated. I need some means for debugging each step in the chain.
Here is a simplified selector as an example:
export const selectCompletedFilesForSaveToServer = state => {
return state
.getIn(['file', 'saveToServerQueue'])
.filterNot(item => item.get('isPosting'))
.valueSeq();
};
And this is what I want to do:
export const selectCompletedFilesForSaveToServer = state => {
return state
.getIn(['file', 'saveToServerQueue'])
.intercept(item => console.log(item.toJS())
.filterNot(item => item.get('isPosting'))
.intercept(item => console.log(item.toJS())
.valueSeq();
};
I.e. the intercept function should take whatever collection is thrown at it (Map, List, etc), iterate over the collection and then return the original collection for further chaining.
I tried to use .forEach(), but I didn't understand how it works.
My current solution is to manually break up the chain into separate intermediate variables for inspection, but this is not a nice solution.
Well.. while writing my question I kind of got some perspective and solved it.
The .filter() function essentially is a peek function. Just remember to return true..
export const selectCompletedFilesForSaveToServer = state => {
return state
.getIn(['file', 'saveToServerQueue'])
.filter(item => {
console.log(item.toJS());
return true;
});
.filterNot(item => item.get('isPosting'))
.filter(item => {
console.log(item.toJS());
return true;
});
.valueSeq();
};
edit:
I found an even better function: .update(). It's chainable and takes a custom function as an argument. The custom function gets the collection as argument and should return the collection as well (in my use case).
https://facebook.github.io/immutable-js/docs/#/Collection/update
New example:
export const selectCompletedFilesForSaveToServer = state => {
const peek = function(collection) {
console.log(collection.toJS());
return collection;
};
return state
.getIn(['file', 'saveToServerQueue'])
.update(peek);
.filterNot(item => item.get('isPosting'))
.update(peek);
.valueSeq();
};
I am following the facebook tutorial and I have a question about the following code:
handleClick(i) {
const squares = this.state.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
squares: squares,
xIsNext: !this.state.xIsNext
});
}
renderSquare(i) {
return <Square value={this.state.squares[i]} onClick={() => this.handleClick(i)} />;
}
Somewhere there exists a Square component but don't worry about it right now. My question is what is going on in the onClick prop. What is on the right side? It looks like ES6 syntax for defining a Javascript function. But are we passing the handleClick function along or calling it? What does that reduce to in ES5?
Isn't this.handleClick(i) immediately calling the handleClick function and not passing it along?
If the body of a function is a single statement, then (when using arrow syntax) you can omit the {} around it.
() => this.handleClick(i)
is equivalent to:
function () { this.handleClick(i); }.bind(this);
this.handleClick(i) <-- calls immediately.
() => this.handleClick(i) <-- is a function. this.handleClick will only be called when the wrapping function is called. The above can be rewritten in es5:
(function () { this.handleClick(i) }).bind(this)
No you create a funtion in that way but you are not calling it in that moment. In that way the context of the created function remains the same as outside it (this). In this way you can call this.handleclick inside because this refers to the outside context
An arrow function does not create its own this context, so this has
its original meaning from the enclosing context.
From arrow funtion