react-hook-forms setValue to empty object does - nothing - react-hook-form

This is the code I am running:
setValue(`myObject.myProperty`, {});
The value of myObject is, before and after running above code, the same.
{
myProperty: { myPropertiesProperty: 1 }
}
Is something obviously wrong here?

Related

Swift computed property return value

I have a computed property that is expected to return an object or nil if it fails.
var findRequest: Book {
get {
var foundRequest: Book!
API.requestBook(book: bookRequest) { book in
if book != nil {
foundRequest = book!
} else {
print("Could not find book")
foundRequest = nil
}
}
return foundRequest
}
}
When I run the code I get an unexpectedly found nil while unwrapping an Optional value error on the return foundRequest line. It looks like the code skips my closure function and goes straight to the return.
Thanks
There are several issues with your implementation. First of all, you shouldn't define foundRequest as an implicitly unwrapped optional if there is a possibility that its value will be nil. Second of all, you are returning the value outside the completion handler of the asynchronous function API.requestBook, so you are returning before foundRequest could get a value and hence you are returning the default value of nil, which will be force unwrapped due to the implicitly unwrapped optional declaration, hence the error.
Moreover, you shouldn't make an asynchronous request inside the getter of a computed property, since computed properties are supposed to return a value right away.
You should completely change your implementation to make findRequest a function returning a value of type Book inside a completion handler.
func findRequest(bookRequest: URLRequest, completion: #escaping (Book?->Void)){
API.requestBook(book: bookRequest) { book in
if let book = book {
completion(book)
} else {
print("Could not find book")
completion(nil)
}
}
}
You can call the function like this:
findRequest(bookRequest: yourRequest, completion: { book in
if let book = book {
//use the returned value
} else {
print("Book not found")
}
})
You might have to change the type of bookRequest from URLRequest depending on what the type of the input parameter book needs to be.
I have a computed property that is expected to return an object or nil if it fails.
Then you should probably define it as:
var findRequest: Book? {
// ...
(note the "?" after Book)
Also, like Martin mentioned in the comments, your computed property's getter is supposed to return a value right away, but you are making what looks like an asynchronous call to retrieve the value. The getter itself returns right away, before the completion handler is called. There is no way the side accessing the property will get the actual value returned by the API.

iOS (ObjC) PromiseKit - Return promise within promise

I'm trying to cascade a promise through some classes which add functionality at each level.
+ (AnyPromise *) method {
return [SomeClass whichReturnsPromise]
.then(^(id obj){
// do stuff
return obj;
});
}
Unfortunately this code is throwing an error on the second line:
exc_bad_access (code=1 address=0x10)
(Note: just calling return [SomeClass whichReturnsPromise] works fine)
I've scoured stackoverflow answers and tried many variations of the above code (which would work in javascript), but I keep getting the same error. How do I fix this?
Turns out a break case for [SomeClass which ReturnsPromise] was returning nil from before it was converted to return a promise. Changed it to return a promise with value nil. Works now.
Without testing, I think the following should work:
[self wait].then(^{
return [SomeClass whichReturnsPromise];
}).then(^(id obj) {
return obj;
});
I know the following is Swift, but if you have an AnyPromise you can use it in a Promise<T> chain:
someSwiftPromise().then { _ -> AnyPromise in
// provided by `pod PromiseKit/SystemConfiguration`
return SCNetworkReachability()
}.then { (obj: AnyObject?) in
// AnyPromise always resolves with `AnyObject?`
}

Dart: List remove not removing Object

The code is on DartPad if you need a complete example (see the while loop towards the end.)
I have a loop,
Place place = places[0];
while (places.isNotEmpty) {
// Get a list of places within distance (we can travel to)
List reachables = place.getReachables();
// Get the closest reachable place
Place closest = place.getClosest(reachables);
// Remove the current place (ultimately should terminate the loop)
places.remove(place);
// Iterate
place = closest;
}
But it's not removing place on the second-to-last line. i.e., the length of the places list remains the same, making it an infinite loop. What's wrong?
This could be because the object in the list has a different hashCode from the object you are trying to remove.
Try using this code instead, to find the correct object by comparing the objects properties, before removing it:
var item = list.firstWhere((x) => x.property1== myObj.property1 && x.property2== myObj.property2, orElse: () => null);
list.remove(item);
Another option is to override the == operator and hashCode in your class.
class Class1 {
#override
bool operator==(other) {
if(other is! Class1) {
return false;
}
return property1 == (other as Class1).property1;
}
int _hashCode;
#override
int get hashCode {
if(_hashCode == null) {
_hashCode = property1.hashCode
}
return _hashCode;
}
}
I have faced the very same issue. Unfortunately I haven't found the root cause, but in the same situation I replaced
places.remove[place]
with
places.removeWhere(p => p.hachCode == place.hashCode)
as a workaround. One more approach was helpful too:
// Get the place from your set:
final place = places.first;
// Replace the place in the set:
places.add(place);
// Remove the place from the set:
places.remove(place);
Most likely place is not in the list for some reason. It's hard to debug without knowing the exact data used, the problem doesn't reproduce with the three-place sample you have in the linked DartPad.
Try figuring out which element is causing the problem. For example you can
try adding an if (!places.contains(place)) print("!!! $place not in $places"); before the remove, or something similar that detects the state when the problem occurs.
This way you can remove object from dynamic list
List data = [
{
"name":"stack"
},
{
"name":"overflow"
}
];
data.removeWhere((item) => item["name"]=="stack");
print(data);
Output
[{name: overflow}]
Use the plugin Equatable
class Place extends Equatable {
...
}
https://pub.dev/packages/equatable
I was having the same issue. I did something like this using removeWhere.
myList.removeWhere((item) => item.id == yourItemId.id)

Neo4j: Get the value for a deleted property

I am using transaction event handlers to do security checking on deleted nodes, to make sure whether a current user is allowed to do this.
To make sure I have the right node to check I first have to find out whether it has a certain property and then check the value of another property, so ideally the code should be something like this:
graphDatabaseService.registerTransactionEventHandler(new TransactionEventHandler.Adapter<Object>() {
#Override
public Object beforeCommit(TransactionData data) throws Exception {
for (Node node : data.deletedNodes()) {
if (node.hasProperty("checkProperty")){
if (node.hasProperty("propertyToCheck")){
String value = (String) node.getProperty("propertyToCheck");
... do checking on value
}
}
}
return null;
}
But this fails with exception
Caused by: java.lang.IllegalStateException: Node[11] has been deleted in this tx
at org.neo4j.kernel.impl.core.WritableTransactionState$CowEntityElement.assertNotDeleted(WritableTransactionState.java:141)
at org.neo4j.kernel.impl.core.WritableTransactionState$CowEntityElement.getPropertyAddMap(WritableTransactionState.java:129)
at org.neo4j.kernel.impl.core.WritableTransactionState$CowNodeElement.getPropertyAddMap(WritableTransactionState.java:155)
at org.neo4j.kernel.impl.core.WritableTransactionState.getCowPropertyAddMap(WritableTransactionState.java:529)
at org.neo4j.kernel.impl.core.Primitive.hasProperty(Primitive.java:306)
at org.neo4j.kernel.impl.core.NodeImpl.hasProperty(NodeImpl.java:53)
at org.neo4j.kernel.impl.core.NodeProxy.hasProperty(NodeProxy.java:160)
The only workaround I found is this:
for (Node node : data.deletedNodes()) {
boolean check = false;
String valueToCheck = null;
for (PropertyEntry prop : data.removedNodeProperties()) {
if (node.equals(prop.entity())) {
if (prop.key().equals("checkProperty")) {
check = true;
}
if (prop.key().equals("propertyToCheck")) {
valueToCheck = (String) prop.previouslyCommitedValue();
}
}
}
if (check){
... do checking on value
}
}
But this goes through ALL deleted properties, so this is obviously not a nice solution.
So my question is: is there a better way to do this?
Using neo4j 1.9.3
Since the code in TransactionEventHandler#beforeCommit is itself part of the transaction you cannot access any property on a deleted node or relationship. As you've discovered the only way to access deleted properties is via TransactionData#removedNodeProperties() and TransactionData#removedRelationshipProperties().
You can optimize your code by running a single iteration over removedNodeProperties() (just pseudo code below):
for (PropertyEntry<Node> pe: data.removedNodeProperties()) {
if (pe.key().equals("checkProperty")) {
runCheckForDeletedNodeAndValue(pe.entity(), pe.previouslyCommitedValue())
}
}
public void runCheckForDeletedNodeAndValue(Node node, Object oldValue) {
// throw exception if current user is not allowed to delete
// this will rollback whole transaction
}
Your snippet would iterate this collection for each deleted node.

Returning NULL Structure

I am calling a function which returns a structure of the type CvBox2D, however I want to check for an error in the function and return NULL if there is an error.
CvBox2D function()
{
...
if(ERROR)
return NULL;
...
}
I am getting an error : cannot convert from 'int' to 'CvBox2D'
Your function return type is CvBox2D, so you can't convert a (NULL) pointer to it.
If you really need to return "nothing" if the check inside the function fails, you can change the return type to a pointer to CvBox2D:
CvBox2D* function()
{
...
}
You will also have to change the way the returned object is created inside your function.
Note that using raw pointers in C++ usually isn't a good idea.
Take a look at std::shared_ptr (available in C++11) if you think you really have to use pointers.
If you want to return some error code, you can do the following:
int function(CvBox2D* output) {
// code...
// Assign to struct.
output->center = ...;
if (error) {
return RC_ERROR_FOO;
}
return RC_OK;
}
Then you call this function using a struct you've already allocated (for example, on the stack):
{
CvBox2D myBox;
int retval = function(&myBox);
if (RC_OK == retval) {
printf("Good! Angle of box: %g", myBox.angle);
} else {
printf("Error: %d", retval);
}
}
Where RC_OK, RC_ERROR_FOO are defined as constant integers, or better, as an enum (if you're using C++).
The other answers solve your problem, but if you want to keep the signature of your function, instead of returning an error code, you should throw an exception.

Resources